diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/cloudrun-auth-http-client.iml b/.idea/cloudrun-auth-http-client.iml new file mode 100644 index 0000000..83d73f7 --- /dev/null +++ b/.idea/cloudrun-auth-http-client.iml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeception.xml b/.idea/codeception.xml new file mode 100644 index 0000000..70e3d14 --- /dev/null +++ b/.idea/codeception.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..b8dedd6 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/php.xml b/.idea/php.xml new file mode 100644 index 0000000..6e33d2b --- /dev/null +++ b/.idea/php.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/phpspec.xml b/.idea/phpspec.xml new file mode 100644 index 0000000..c7cfbc2 --- /dev/null +++ b/.idea/phpspec.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/phpunit.xml b/.idea/phpunit.xml new file mode 100644 index 0000000..4f8104c --- /dev/null +++ b/.idea/phpunit.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..16d89aa --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Joan Fabrégat / Code Inc. SAS + +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. \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..564e89a --- /dev/null +++ b/composer.json @@ -0,0 +1,38 @@ +{ + "name": "codeinc/cloudrun-auth-http-client", + "version": "v1.0", + "description": "A PSR-7 HTTP client based on Guzzle for services hosted on Google Cloud Platform Cloud Run", + "homepage": "https://github.com/codeinchq/cloudrun-auth-http-client", + "type": "library", + "license": "MIT", + "require": { + "php": ">=8.2", + "google/auth": "^1.35", + "guzzlehttp/guzzle": "^7.8", + "psr/http-client": "^1.0" + }, + "autoload": { + "psr-4": { + "CodeInc\\CloudrunAuthHttpClient\\": "src" + } + }, + "authors": [ + { + "name": "Joan Fabrégat", + "email": "joan@codeinc.co", + "homepage": "https://www.codeinc.co", + "role": "developer" + } + ], + "config": { + "preferred-install": { + "*": "dist" + }, + "allow-plugins": { + "php-http/discovery": true + } + }, + "require-dev": { + "squizlabs/php_codesniffer": "^3.8" + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..29543ed --- /dev/null +++ b/composer.lock @@ -0,0 +1,868 @@ +{ + "_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": "f4847681959bfaaa9118ce27979e1c3f", + "packages": [ + { + "name": "firebase/php-jwt", + "version": "v6.10.0", + "source": { + "type": "git", + "url": "https://github.com/firebase/php-jwt.git", + "reference": "a49db6f0a5033aef5143295342f1c95521b075ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/a49db6f0a5033aef5143295342f1c95521b075ff", + "reference": "a49db6f0a5033aef5143295342f1c95521b075ff", + "shasum": "" + }, + "require": { + "php": "^7.4||^8.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "type": "library", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v6.10.0" + }, + "time": "2023-12-01T16:26:39+00:00" + }, + { + "name": "google/auth", + "version": "v1.35.0", + "source": { + "type": "git", + "url": "https://github.com/googleapis/google-auth-library-php.git", + "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", + "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "^6.0", + "guzzlehttp/guzzle": "^6.5.8||^7.4.5", + "guzzlehttp/psr7": "^2.4.5", + "php": "^7.4||^8.0", + "psr/cache": "^1.0||^2.0||^3.0", + "psr/http-message": "^1.1||^2.0" + }, + "require-dev": { + "guzzlehttp/promises": "^2.0", + "kelvinmo/simplejwt": "0.7.1", + "phpseclib/phpseclib": "^3.0", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.0.0", + "sebastian/comparator": ">=1.2.3", + "squizlabs/php_codesniffer": "^3.5" + }, + "suggest": { + "phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings or for token management. Please require version ^2." + }, + "type": "library", + "autoload": { + "psr-4": { + "Google\\Auth\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Google Auth Library for PHP", + "homepage": "http://github.com/google/google-auth-library-php", + "keywords": [ + "Authentication", + "google", + "oauth2" + ], + "support": { + "docs": "https://googleapis.github.io/google-auth-library-php/main/", + "issues": "https://github.com/googleapis/google-auth-library-php/issues", + "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.35.0" + }, + "time": "2024-02-01T20:41:08+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.8.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.8.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:35:24+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:19:20+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.6.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.6.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2023-12-03T20:05:35+00:00" + }, + { + "name": "psr/cache", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/cache.git", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/cache/zipball/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for caching libraries", + "keywords": [ + "cache", + "psr", + "psr-6" + ], + "support": { + "source": "https://github.com/php-fig/cache/tree/3.0.0" + }, + "time": "2021-02-03T23:26:27+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "e616d01114759c4c489f93b099585439f795fe35" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35", + "reference": "e616d01114759c4c489f93b099585439f795fe35", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/1.0.2" + }, + "time": "2023-04-10T20:10:41+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+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" + } + ], + "packages-dev": [ + { + "name": "squizlabs/php_codesniffer", + "version": "3.8.1", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", + "reference": "14f5fff1e64118595db5408e946f3a22c75807f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/14f5fff1e64118595db5408e946f3a22c75807f7", + "reference": "14f5fff1e64118595db5408e946f3a22c75807f7", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" + }, + "bin": [ + "bin/phpcbf", + "bin/phpcs" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "Former lead" + }, + { + "name": "Juliette Reinders Folmer", + "role": "Current lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", + "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy", + "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + } + ], + "time": "2024-01-11T20:47:48+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=8.2" + }, + "platform-dev": [], + "plugin-api-version": "2.6.0" +} diff --git a/src/HttpClientFactory.php b/src/HttpClientFactory.php new file mode 100644 index 0000000..0b89a09 --- /dev/null +++ b/src/HttpClientFactory.php @@ -0,0 +1,74 @@ + for more information + */ + +declare(strict_types=1); + +namespace CodeInc\CloudrunAuthHttpClient; + +use Google\Auth\Credentials\ServiceAccountCredentials; +use Google\Auth\Middleware\AuthTokenMiddleware; +use GuzzleHttp\Client; +use GuzzleHttp\HandlerStack; + +/** + * @see https://github.com/googleapis/google-auth-library-php + */ +final readonly class HttpClientFactory +{ + /** + * @param array|string $jsonKey + * @param string $serviceUrl + * @return Client + */ + public function factory(array|string $jsonKey, string $serviceUrl): Client + { + return new Client([ + 'handler' => $this->createHttpClientHandler($jsonKey, $serviceUrl), + 'auth' => 'google_auth', + 'base_uri' => $serviceUrl, + ]); + } + + /** + * @param array|string $jsonKey + * @param string $serviceUrl + * @return HandlerStack + */ + private function createHttpClientHandler(array|string $jsonKey, string $serviceUrl): HandlerStack + { + $stack = HandlerStack::create(); + $stack->push($this->createMiddleware($jsonKey, $serviceUrl)); + return $stack; + } + + /** + * @param array|string $jsonKey + * @param string $serviceUrl + * @return AuthTokenMiddleware + */ + private function createMiddleware(array|string $jsonKey, string $serviceUrl): AuthTokenMiddleware + { + return new AuthTokenMiddleware( + $this->getServiceAccountCredentials($jsonKey, $serviceUrl) + ); + } + + /** + * @param array|string $jsonKey + * @param string $targetAudience + * @return ServiceAccountCredentials + */ + private function getServiceAccountCredentials(array|string $jsonKey, string $targetAudience): ServiceAccountCredentials + { + return new ServiceAccountCredentials( + scope: null, + jsonKey: $jsonKey, + targetAudience: $targetAudience + ); + } +} diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 0000000..c57a2a2 --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,25 @@ +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_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/squizlabs/php_codesniffer/bin/phpcbf'); + } +} + +return include __DIR__ . '/..'.'/squizlabs/php_codesniffer/bin/phpcbf'; diff --git a/vendor/bin/phpcs b/vendor/bin/phpcs new file mode 100755 index 0000000..04e658c --- /dev/null +++ b/vendor/bin/phpcs @@ -0,0 +1,119 @@ +#!/usr/bin/env php +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_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true)) + || (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) + ) { + return include("phpvfscomposer://" . __DIR__ . '/..'.'/squizlabs/php_codesniffer/bin/phpcs'); + } +} + +return include __DIR__ . '/..'.'/squizlabs/php_codesniffer/bin/phpcs'; diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php new file mode 100644 index 0000000..7824d8f --- /dev/null +++ b/vendor/composer/ClassLoader.php @@ -0,0 +1,579 @@ + + * 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 \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @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 list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $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 list|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) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $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] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $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 list|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 list|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 = self::$includeFile; + $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 keyed by their corresponding vendor directories. + * + * @return array + */ + 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; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..51e734a --- /dev/null +++ b/vendor/composer/InstalledVersions.php @@ -0,0 +1,359 @@ + + * 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` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, 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 || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + 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((string) $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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + 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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, 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, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, 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')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; + 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') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/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/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..0fb0a2c --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 0000000..ff3bac2 --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,12 @@ + $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), + 'Psr\\Cache\\' => array($vendorDir . '/psr/cache/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'Google\\Auth\\' => array($vendorDir . '/google/auth/src'), + 'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'), + 'CodeInc\\CloudrunAuthHttpClient\\' => array($baseDir . '/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 0000000..312bb35 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,50 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInitf4847681959bfaaa9118ce27979e1c3f::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }, null, null); + foreach ($filesToLoad as $fileIdentifier => $file) { + $requireFile($fileIdentifier, $file); + } + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..78bba5d --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,92 @@ + __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'P' => + array ( + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, + 'Psr\\Cache\\' => 10, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + 'Google\\Auth\\' => 12, + ), + 'F' => + array ( + 'Firebase\\JWT\\' => 13, + ), + 'C' => + array ( + 'CodeInc\\CloudrunAuthHttpClient\\' => 31, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + 1 => __DIR__ . '/..' . '/psr/http-factory/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'Psr\\Cache\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/cache/src', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'Google\\Auth\\' => + array ( + 0 => __DIR__ . '/..' . '/google/auth/src', + ), + 'Firebase\\JWT\\' => + array ( + 0 => __DIR__ . '/..' . '/firebase/php-jwt/src', + ), + 'CodeInc\\CloudrunAuthHttpClient\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitf4847681959bfaaa9118ce27979e1c3f::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitf4847681959bfaaa9118ce27979e1c3f::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitf4847681959bfaaa9118ce27979e1c3f::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 0000000..577f0e1 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,890 @@ +{ + "packages": [ + { + "name": "firebase/php-jwt", + "version": "v6.10.0", + "version_normalized": "6.10.0.0", + "source": { + "type": "git", + "url": "https://github.com/firebase/php-jwt.git", + "reference": "a49db6f0a5033aef5143295342f1c95521b075ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/a49db6f0a5033aef5143295342f1c95521b075ff", + "reference": "a49db6f0a5033aef5143295342f1c95521b075ff", + "shasum": "" + }, + "require": { + "php": "^7.4||^8.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "time": "2023-12-01T16:26:39+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v6.10.0" + }, + "install-path": "../firebase/php-jwt" + }, + { + "name": "google/auth", + "version": "v1.35.0", + "version_normalized": "1.35.0.0", + "source": { + "type": "git", + "url": "https://github.com/googleapis/google-auth-library-php.git", + "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/googleapis/google-auth-library-php/zipball/6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", + "reference": "6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "^6.0", + "guzzlehttp/guzzle": "^6.5.8||^7.4.5", + "guzzlehttp/psr7": "^2.4.5", + "php": "^7.4||^8.0", + "psr/cache": "^1.0||^2.0||^3.0", + "psr/http-message": "^1.1||^2.0" + }, + "require-dev": { + "guzzlehttp/promises": "^2.0", + "kelvinmo/simplejwt": "0.7.1", + "phpseclib/phpseclib": "^3.0", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.0.0", + "sebastian/comparator": ">=1.2.3", + "squizlabs/php_codesniffer": "^3.5" + }, + "suggest": { + "phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings or for token management. Please require version ^2." + }, + "time": "2024-02-01T20:41:08+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Google\\Auth\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Google Auth Library for PHP", + "homepage": "http://github.com/google/google-auth-library-php", + "keywords": [ + "Authentication", + "google", + "oauth2" + ], + "support": { + "docs": "https://googleapis.github.io/google-auth-library-php/main/", + "issues": "https://github.com/googleapis/google-auth-library-php/issues", + "source": "https://github.com/googleapis/google-auth-library-php/tree/v1.35.0" + }, + "install-path": "../google/auth" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.8.1", + "version_normalized": "7.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/41042bc7ab002487b876a0683fc8dce04ddce104", + "reference": "41042bc7ab002487b876a0683fc8dce04ddce104", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2023-12-03T20:35:24+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.8.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/promises", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/bbff78d96034045e58e13dedd6ad91b5d1253223", + "reference": "bbff78d96034045e58e13dedd6ad91b5d1253223", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "time": "2023-12-03T20:19:20+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/promises" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.6.2", + "version_normalized": "2.6.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/45b30f99ac27b5ca93cb4831afe16285f57b8221", + "reference": "45b30f99ac27b5ca93cb4831afe16285f57b8221", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2023-12-03T20:05:35+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.6.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "psr/cache", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/cache.git", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/cache/zipball/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-02-03T23:26:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for caching libraries", + "keywords": [ + "cache", + "psr", + "psr-6" + ], + "support": { + "source": "https://github.com/php-fig/cache/tree/3.0.0" + }, + "install-path": "../psr/cache" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "version_normalized": "1.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-09-23T14:17:50+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "install-path": "../psr/http-client" + }, + { + "name": "psr/http-factory", + "version": "1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "e616d01114759c4c489f93b099585439f795fe35" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/e616d01114759c4c489f93b099585439f795fe35", + "reference": "e616d01114759c4c489f93b099585439f795fe35", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "time": "2023-04-10T20:10:41+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/1.0.2" + }, + "install-path": "../psr/http-factory" + }, + { + "name": "psr/http-message", + "version": "2.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "time": "2023-04-04T09:54:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "install-path": "../psr/http-message" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "install-path": "../ralouphie/getallheaders" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.8.1", + "version_normalized": "3.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", + "reference": "14f5fff1e64118595db5408e946f3a22c75807f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/14f5fff1e64118595db5408e946f3a22c75807f7", + "reference": "14f5fff1e64118595db5408e946f3a22c75807f7", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" + }, + "time": "2024-01-11T20:47:48+00:00", + "bin": [ + "bin/phpcbf", + "bin/phpcs" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "Former lead" + }, + { + "name": "Juliette Reinders Folmer", + "role": "Current lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", + "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy", + "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + } + ], + "install-path": "../squizlabs/php_codesniffer" + }, + { + "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" + } + ], + "dev": true, + "dev-package-names": [ + "squizlabs/php_codesniffer" + ] +} diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php new file mode 100644 index 0000000..968bc02 --- /dev/null +++ b/vendor/composer/installed.php @@ -0,0 +1,149 @@ + array( + 'name' => 'codeinc/cloudrun-auth-http-client', + 'pretty_version' => 'v1.0', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'codeinc/cloudrun-auth-http-client' => array( + 'pretty_version' => 'v1.0', + 'version' => '1.0.0.0', + 'reference' => NULL, + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'firebase/php-jwt' => array( + 'pretty_version' => 'v6.10.0', + 'version' => '6.10.0.0', + 'reference' => 'a49db6f0a5033aef5143295342f1c95521b075ff', + 'type' => 'library', + 'install_path' => __DIR__ . '/../firebase/php-jwt', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'google/auth' => array( + 'pretty_version' => 'v1.35.0', + 'version' => '1.35.0.0', + 'reference' => '6e9c9fd4e2bbd7042f50083076346e4a1eff4e4b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../google/auth', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/guzzle' => array( + 'pretty_version' => '7.8.1', + 'version' => '7.8.1.0', + 'reference' => '41042bc7ab002487b876a0683fc8dce04ddce104', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/guzzle', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/promises' => array( + 'pretty_version' => '2.0.2', + 'version' => '2.0.2.0', + 'reference' => 'bbff78d96034045e58e13dedd6ad91b5d1253223', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/promises', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '2.6.2', + 'version' => '2.6.2.0', + 'reference' => '45b30f99ac27b5ca93cb4831afe16285f57b8221', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/cache' => array( + 'pretty_version' => '3.0.0', + 'version' => '3.0.0.0', + 'reference' => 'aa5030cfa5405eccfdcb1083ce040c2cb8d253bf', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/cache', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client' => array( + 'pretty_version' => '1.0.3', + 'version' => '1.0.3.0', + 'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.0.2', + 'version' => '1.0.2.0', + 'reference' => 'e616d01114759c4c489f93b099585439f795fe35', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '2.0', + 'version' => '2.0.0.0', + 'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'squizlabs/php_codesniffer' => array( + 'pretty_version' => '3.8.1', + 'version' => '3.8.1.0', + 'reference' => '14f5fff1e64118595db5408e946f3a22c75807f7', + 'type' => 'library', + 'install_path' => __DIR__ . '/../squizlabs/php_codesniffer', + 'aliases' => array(), + 'dev_requirement' => true, + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v3.4.0', + 'version' => '3.4.0.0', + 'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php new file mode 100644 index 0000000..d32d90c --- /dev/null +++ b/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/vendor/firebase/php-jwt/CHANGELOG.md b/vendor/firebase/php-jwt/CHANGELOG.md new file mode 100644 index 0000000..644fa0b --- /dev/null +++ b/vendor/firebase/php-jwt/CHANGELOG.md @@ -0,0 +1,170 @@ +# Changelog + +## [6.10.0](https://github.com/firebase/php-jwt/compare/v6.9.0...v6.10.0) (2023-11-28) + + +### Features + +* allow typ header override ([#546](https://github.com/firebase/php-jwt/issues/546)) ([79cb30b](https://github.com/firebase/php-jwt/commit/79cb30b729a22931b2fbd6b53f20629a83031ba9)) + +## [6.9.0](https://github.com/firebase/php-jwt/compare/v6.8.1...v6.9.0) (2023-10-04) + + +### Features + +* add payload to jwt exception ([#521](https://github.com/firebase/php-jwt/issues/521)) ([175edf9](https://github.com/firebase/php-jwt/commit/175edf958bb61922ec135b2333acf5622f2238a2)) + +## [6.8.1](https://github.com/firebase/php-jwt/compare/v6.8.0...v6.8.1) (2023-07-14) + + +### Bug Fixes + +* accept float claims but round down to ignore them ([#492](https://github.com/firebase/php-jwt/issues/492)) ([3936842](https://github.com/firebase/php-jwt/commit/39368423beeaacb3002afa7dcb75baebf204fe7e)) +* different BeforeValidException messages for nbf and iat ([#526](https://github.com/firebase/php-jwt/issues/526)) ([0a53cf2](https://github.com/firebase/php-jwt/commit/0a53cf2986e45c2bcbf1a269f313ebf56a154ee4)) + +## [6.8.0](https://github.com/firebase/php-jwt/compare/v6.7.0...v6.8.0) (2023-06-14) + + +### Features + +* add support for P-384 curve ([#515](https://github.com/firebase/php-jwt/issues/515)) ([5de4323](https://github.com/firebase/php-jwt/commit/5de4323f4baf4d70bca8663bd87682a69c656c3d)) + + +### Bug Fixes + +* handle invalid http responses ([#508](https://github.com/firebase/php-jwt/issues/508)) ([91c39c7](https://github.com/firebase/php-jwt/commit/91c39c72b22fc3e1191e574089552c1f2041c718)) + +## [6.7.0](https://github.com/firebase/php-jwt/compare/v6.6.0...v6.7.0) (2023-06-14) + + +### Features + +* add ed25519 support to JWK (public keys) ([#452](https://github.com/firebase/php-jwt/issues/452)) ([e53979a](https://github.com/firebase/php-jwt/commit/e53979abae927de916a75b9d239cfda8ce32be2a)) + +## [6.6.0](https://github.com/firebase/php-jwt/compare/v6.5.0...v6.6.0) (2023-06-13) + + +### Features + +* allow get headers when decoding token ([#442](https://github.com/firebase/php-jwt/issues/442)) ([fb85f47](https://github.com/firebase/php-jwt/commit/fb85f47cfaeffdd94faf8defdf07164abcdad6c3)) + + +### Bug Fixes + +* only check iat if nbf is not used ([#493](https://github.com/firebase/php-jwt/issues/493)) ([398ccd2](https://github.com/firebase/php-jwt/commit/398ccd25ea12fa84b9e4f1085d5ff448c21ec797)) + +## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12) + + +### Bug Fixes + +* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a)) + + +### Miscellaneous Chores + +* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495)) + +## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08) + + +### Features + +* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95)) +* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c)) + +## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01) + + +### Bug Fixes + +* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd)) + +## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01) + + +### Bug Fixes + +* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22)) +* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2)) + +## 6.3.0 / 2022-07-15 + + - Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399)) + - Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435)) + +## 6.2.0 / 2022-05-14 + + - Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397)) + - Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)). + +## 6.1.0 / 2022-03-23 + + - Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0 + - Add parameter typing and return types where possible + +## 6.0.0 / 2022-01-24 + + - **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information. + - New Key object to prevent key/algorithm type confusion (#365) + - Add JWK support (#273) + - Add ES256 support (#256) + - Add ES384 support (#324) + - Add Ed25519 support (#343) + +## 5.0.0 / 2017-06-26 +- Support RS384 and RS512. + See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)! +- Add an example for RS256 openssl. + See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)! +- Detect invalid Base64 encoding in signature. + See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)! +- Update `JWT::verify` to handle OpenSSL errors. + See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)! +- Add `array` type hinting to `decode` method + See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)! +- Add all JSON error types. + See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)! +- Bugfix 'kid' not in given key list. + See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)! +- Miscellaneous cleanup, documentation and test fixes. + See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115), + [#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and + [#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman), + [@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)! + +## 4.0.0 / 2016-07-17 +- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)! +- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)! +- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)! +- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)! + +## 3.0.0 / 2015-07-22 +- Minimum PHP version updated from `5.2.0` to `5.3.0`. +- Add `\Firebase\JWT` namespace. See +[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to +[@Dashron](https://github.com/Dashron)! +- Require a non-empty key to decode and verify a JWT. See +[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to +[@sjones608](https://github.com/sjones608)! +- Cleaner documentation blocks in the code. See +[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to +[@johanderuijter](https://github.com/johanderuijter)! + +## 2.2.0 / 2015-06-22 +- Add support for adding custom, optional JWT headers to `JWT::encode()`. See +[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to +[@mcocaro](https://github.com/mcocaro)! + +## 2.1.0 / 2015-05-20 +- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew +between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)! +- Add support for passing an object implementing the `ArrayAccess` interface for +`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)! + +## 2.0.0 / 2015-04-01 +- **Note**: It is strongly recommended that you update to > v2.0.0 to address + known security vulnerabilities in prior versions when both symmetric and + asymmetric keys are used together. +- Update signature for `JWT::decode(...)` to require an array of supported + algorithms to use when verifying token signatures. diff --git a/vendor/firebase/php-jwt/LICENSE b/vendor/firebase/php-jwt/LICENSE new file mode 100644 index 0000000..11c0146 --- /dev/null +++ b/vendor/firebase/php-jwt/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2011, Neuman Vong + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * Neither the name of the copyright holder nor the names of other + 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 +OWNER 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/vendor/firebase/php-jwt/README.md b/vendor/firebase/php-jwt/README.md new file mode 100644 index 0000000..701de23 --- /dev/null +++ b/vendor/firebase/php-jwt/README.md @@ -0,0 +1,424 @@ +![Build Status](https://github.com/firebase/php-jwt/actions/workflows/tests.yml/badge.svg) +[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt) +[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt) +[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt) + +PHP-JWT +======= +A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519). + +Installation +------------ + +Use composer to manage your dependencies and download PHP-JWT: + +```bash +composer require firebase/php-jwt +``` + +Optionally, install the `paragonie/sodium_compat` package from composer if your +php is < 7.2 or does not have libsodium installed: + +```bash +composer require paragonie/sodium_compat +``` + +Example +------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$key = 'example_key'; +$payload = [ + 'iss' => 'http://example.org', + 'aud' => 'http://example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +/** + * IMPORTANT: + * You must specify supported algorithms for your application. See + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 + * for a list of spec-compliant algorithms. + */ +$jwt = JWT::encode($payload, $key, 'HS256'); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +print_r($decoded); + +// Pass a stdClass in as the third parameter to get the decoded header values +$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers = new stdClass()); +print_r($headers); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; + +/** + * You can add a leeway to account for when there is a clock skew times between + * the signing and verifying servers. It is recommended that this leeway should + * not be bigger than a few minutes. + * + * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef + */ +JWT::$leeway = 60; // $leeway in seconds +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +``` +Example encode/decode headers +------- +Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by +this library. This is because without verifying the JWT, the header values could have been tampered with. +Any value pulled from an unverified header should be treated as if it could be any string sent in from an +attacker. If this is something you still want to do in your application for whatever reason, it's possible to +decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT +header part: +```php +use Firebase\JWT\JWT; + +$key = 'example_key'; +$payload = [ + 'iss' => 'http://example.org', + 'aud' => 'http://example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$headers = [ + 'x-forwarded-for' => 'www.google.com' +]; + +// Encode headers in the JWT string +$jwt = JWT::encode($payload, $key, 'HS256', null, $headers); + +// Decode headers from the JWT string WITHOUT validation +// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified. +// These headers could be any value sent by an attacker. +list($headersB64, $payloadB64, $sig) = explode('.', $jwt); +$decoded = json_decode(base64_decode($headersB64), true); + +print_r($decoded); +``` +Example with RS256 (openssl) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$privateKey = << 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; +echo "Decode:\n" . print_r($decoded_array, true) . "\n"; +``` + +Example with a passphrase +------------------------- + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Your passphrase +$passphrase = '[YOUR_PASSPHRASE]'; + +// Your private key file with passphrase +// Can be generated with "ssh-keygen -t rsa -m pem" +$privateKeyFile = '/path/to/key-with-passphrase.pem'; + +// Create a private key of type "resource" +$privateKey = openssl_pkey_get_private( + file_get_contents($privateKeyFile), + $passphrase +); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +// Get public key from the private key, or pull from from a file. +$publicKey = openssl_pkey_get_details($privateKey)['key']; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +Example with EdDSA (libsodium and Ed25519 signature) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Public and private keys are expected to be Base64 encoded. The last +// non-empty line is used so that keys can be generated with +// sodium_crypto_sign_keypair(). The secret keys generated by other tools may +// need to be adjusted to match the input expected by libsodium. + +$keyPair = sodium_crypto_sign_keypair(); + +$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair)); + +$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair)); + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt = JWT::encode($payload, $privateKey, 'EdDSA'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +```` + +Example with multiple keys +-------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Example RSA keys from previous example +// $privateKey1 = '...'; +// $publicKey1 = '...'; + +// Example EdDSA keys from previous example +// $privateKey2 = '...'; +// $publicKey2 = '...'; + +$payload = [ + 'iss' => 'example.org', + 'aud' => 'example.com', + 'iat' => 1356999524, + 'nbf' => 1357000000 +]; + +$jwt1 = JWT::encode($payload, $privateKey1, 'RS256', 'kid1'); +$jwt2 = JWT::encode($payload, $privateKey2, 'EdDSA', 'kid2'); +echo "Encode 1:\n" . print_r($jwt1, true) . "\n"; +echo "Encode 2:\n" . print_r($jwt2, true) . "\n"; + +$keys = [ + 'kid1' => new Key($publicKey1, 'RS256'), + 'kid2' => new Key($publicKey2, 'EdDSA'), +]; + +$decoded1 = JWT::decode($jwt1, $keys); +$decoded2 = JWT::decode($jwt2, $keys); + +echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n"; +echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n"; +``` + +Using JWKs +---------- + +```php +use Firebase\JWT\JWK; +use Firebase\JWT\JWT; + +// Set of keys. The "keys" key is required. For example, the JSON response to +// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk +$jwks = ['keys' => []]; + +// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key +// objects. Pass this as the second parameter to JWT::decode. +JWT::decode($payload, JWK::parseKeySet($jwks)); +``` + +Using Cached Key Sets +--------------------- + +The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI. +This has the following advantages: + +1. The results are cached for performance. +2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation. +3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second. + +```php +use Firebase\JWT\CachedKeySet; +use Firebase\JWT\JWT; + +// The URI for the JWKS you wish to cache the results from +$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk'; + +// Create an HTTP client (can be any PSR-7 compatible HTTP client) +$httpClient = new GuzzleHttp\Client(); + +// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory) +$httpFactory = new GuzzleHttp\Psr\HttpFactory(); + +// Create a cache item pool (can be any PSR-6 compatible cache item pool) +$cacheItemPool = Phpfastcache\CacheManager::getInstance('files'); + +$keySet = new CachedKeySet( + $jwksUri, + $httpClient, + $httpFactory, + $cacheItemPool, + null, // $expiresAfter int seconds to set the JWKS to expire + true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys +); + +$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above +$decoded = JWT::decode($jwt, $keySet); +``` + +Miscellaneous +------------- + +#### Exception Handling + +When a call to `JWT::decode` is invalid, it will throw one of the following exceptions: + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\SignatureInvalidException; +use Firebase\JWT\BeforeValidException; +use Firebase\JWT\ExpiredException; +use DomainException; +use InvalidArgumentException; +use UnexpectedValueException; + +try { + $decoded = JWT::decode($payload, $keys); +} catch (InvalidArgumentException $e) { + // provided key/key-array is empty or malformed. +} catch (DomainException $e) { + // provided algorithm is unsupported OR + // provided key is invalid OR + // unknown error thrown in openSSL or libsodium OR + // libsodium is required but not available. +} catch (SignatureInvalidException $e) { + // provided JWT signature verification failed. +} catch (BeforeValidException $e) { + // provided JWT is trying to be used before "nbf" claim OR + // provided JWT is trying to be used before "iat" claim. +} catch (ExpiredException $e) { + // provided JWT is trying to be used after "exp" claim. +} catch (UnexpectedValueException $e) { + // provided JWT is malformed OR + // provided JWT is missing an algorithm / using an unsupported algorithm OR + // provided JWT algorithm does not match provided key OR + // provided key ID in key/key-array is empty or invalid. +} +``` + +All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified +like this: + +```php +use Firebase\JWT\JWT; +use UnexpectedValueException; +try { + $decoded = JWT::decode($payload, $keys); +} catch (LogicException $e) { + // errors having to do with environmental setup or malformed JWT Keys +} catch (UnexpectedValueException $e) { + // errors having to do with JWT signature and claims +} +``` + +#### Casting to array + +The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays +instead, you can do the following: + +```php +// return type is stdClass +$decoded = JWT::decode($payload, $keys); + +// cast to array +$decoded = json_decode(json_encode($decoded), true); +``` + +Tests +----- +Run the tests using phpunit: + +```bash +$ pear install PHPUnit +$ phpunit --configuration phpunit.xml.dist +PHPUnit 3.7.10 by Sebastian Bergmann. +..... +Time: 0 seconds, Memory: 2.50Mb +OK (5 tests, 5 assertions) +``` + +New Lines in private keys +----- + +If your private key contains `\n` characters, be sure to wrap it in double quotes `""` +and not single quotes `''` in order to properly interpret the escaped characters. + +License +------- +[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause). diff --git a/vendor/firebase/php-jwt/composer.json b/vendor/firebase/php-jwt/composer.json new file mode 100644 index 0000000..e23dfe3 --- /dev/null +++ b/vendor/firebase/php-jwt/composer.json @@ -0,0 +1,42 @@ +{ + "name": "firebase/php-jwt", + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "php", + "jwt" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "license": "BSD-3-Clause", + "require": { + "php": "^7.4||^8.0" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present", + "ext-sodium": "Support EdDSA (Ed25519) signatures" + }, + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "require-dev": { + "guzzlehttp/guzzle": "^6.5||^7.4", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "psr/cache": "^1.0||^2.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + } +} diff --git a/vendor/firebase/php-jwt/src/BeforeValidException.php b/vendor/firebase/php-jwt/src/BeforeValidException.php new file mode 100644 index 0000000..595164b --- /dev/null +++ b/vendor/firebase/php-jwt/src/BeforeValidException.php @@ -0,0 +1,18 @@ +payload = $payload; + } + + public function getPayload(): object + { + return $this->payload; + } +} diff --git a/vendor/firebase/php-jwt/src/CachedKeySet.php b/vendor/firebase/php-jwt/src/CachedKeySet.php new file mode 100644 index 0000000..ee529f9 --- /dev/null +++ b/vendor/firebase/php-jwt/src/CachedKeySet.php @@ -0,0 +1,268 @@ + + */ +class CachedKeySet implements ArrayAccess +{ + /** + * @var string + */ + private $jwksUri; + /** + * @var ClientInterface + */ + private $httpClient; + /** + * @var RequestFactoryInterface + */ + private $httpFactory; + /** + * @var CacheItemPoolInterface + */ + private $cache; + /** + * @var ?int + */ + private $expiresAfter; + /** + * @var ?CacheItemInterface + */ + private $cacheItem; + /** + * @var array> + */ + private $keySet; + /** + * @var string + */ + private $cacheKey; + /** + * @var string + */ + private $cacheKeyPrefix = 'jwks'; + /** + * @var int + */ + private $maxKeyLength = 64; + /** + * @var bool + */ + private $rateLimit; + /** + * @var string + */ + private $rateLimitCacheKey; + /** + * @var int + */ + private $maxCallsPerMinute = 10; + /** + * @var string|null + */ + private $defaultAlg; + + public function __construct( + string $jwksUri, + ClientInterface $httpClient, + RequestFactoryInterface $httpFactory, + CacheItemPoolInterface $cache, + int $expiresAfter = null, + bool $rateLimit = false, + string $defaultAlg = null + ) { + $this->jwksUri = $jwksUri; + $this->httpClient = $httpClient; + $this->httpFactory = $httpFactory; + $this->cache = $cache; + $this->expiresAfter = $expiresAfter; + $this->rateLimit = $rateLimit; + $this->defaultAlg = $defaultAlg; + $this->setCacheKeys(); + } + + /** + * @param string $keyId + * @return Key + */ + public function offsetGet($keyId): Key + { + if (!$this->keyIdExists($keyId)) { + throw new OutOfBoundsException('Key ID not found'); + } + return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg); + } + + /** + * @param string $keyId + * @return bool + */ + public function offsetExists($keyId): bool + { + return $this->keyIdExists($keyId); + } + + /** + * @param string $offset + * @param Key $value + */ + public function offsetSet($offset, $value): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @param string $offset + */ + public function offsetUnset($offset): void + { + throw new LogicException('Method not implemented'); + } + + /** + * @return array + */ + private function formatJwksForCache(string $jwks): array + { + $jwks = json_decode($jwks, true); + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + $keys = []; + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + $keys[(string) $kid] = $v; + } + + return $keys; + } + + private function keyIdExists(string $keyId): bool + { + if (null === $this->keySet) { + $item = $this->getCacheItem(); + // Try to load keys from cache + if ($item->isHit()) { + // item found! retrieve it + $this->keySet = $item->get(); + // If the cached item is a string, the JWKS response was cached (previous behavior). + // Parse this into expected format array instead. + if (\is_string($this->keySet)) { + $this->keySet = $this->formatJwksForCache($this->keySet); + } + } + } + + if (!isset($this->keySet[$keyId])) { + if ($this->rateLimitExceeded()) { + return false; + } + $request = $this->httpFactory->createRequest('GET', $this->jwksUri); + $jwksResponse = $this->httpClient->sendRequest($request); + if ($jwksResponse->getStatusCode() !== 200) { + throw new UnexpectedValueException( + sprintf('HTTP Error: %d %s for URI "%s"', + $jwksResponse->getStatusCode(), + $jwksResponse->getReasonPhrase(), + $this->jwksUri, + ), + $jwksResponse->getStatusCode() + ); + } + $this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody()); + + if (!isset($this->keySet[$keyId])) { + return false; + } + + $item = $this->getCacheItem(); + $item->set($this->keySet); + if ($this->expiresAfter) { + $item->expiresAfter($this->expiresAfter); + } + $this->cache->save($item); + } + + return true; + } + + private function rateLimitExceeded(): bool + { + if (!$this->rateLimit) { + return false; + } + + $cacheItem = $this->cache->getItem($this->rateLimitCacheKey); + if (!$cacheItem->isHit()) { + $cacheItem->expiresAfter(1); // # of calls are cached each minute + } + + $callsPerMinute = (int) $cacheItem->get(); + if (++$callsPerMinute > $this->maxCallsPerMinute) { + return true; + } + $cacheItem->set($callsPerMinute); + $this->cache->save($cacheItem); + return false; + } + + private function getCacheItem(): CacheItemInterface + { + if (\is_null($this->cacheItem)) { + $this->cacheItem = $this->cache->getItem($this->cacheKey); + } + + return $this->cacheItem; + } + + private function setCacheKeys(): void + { + if (empty($this->jwksUri)) { + throw new RuntimeException('JWKS URI is empty'); + } + + // ensure we do not have illegal characters + $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri); + + // add prefix + $key = $this->cacheKeyPrefix . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($key) > $this->maxKeyLength) { + $key = substr(hash('sha256', $key), 0, $this->maxKeyLength); + } + + $this->cacheKey = $key; + + if ($this->rateLimit) { + // add prefix + $rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key; + + // Hash keys if they exceed $maxKeyLength of 64 + if (\strlen($rateLimitKey) > $this->maxKeyLength) { + $rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength); + } + + $this->rateLimitCacheKey = $rateLimitKey; + } + } +} diff --git a/vendor/firebase/php-jwt/src/ExpiredException.php b/vendor/firebase/php-jwt/src/ExpiredException.php new file mode 100644 index 0000000..12fef09 --- /dev/null +++ b/vendor/firebase/php-jwt/src/ExpiredException.php @@ -0,0 +1,18 @@ +payload = $payload; + } + + public function getPayload(): object + { + return $this->payload; + } +} diff --git a/vendor/firebase/php-jwt/src/JWK.php b/vendor/firebase/php-jwt/src/JWK.php new file mode 100644 index 0000000..63fb248 --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWK.php @@ -0,0 +1,349 @@ + + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWK +{ + private const OID = '1.2.840.10045.2.1'; + private const ASN1_OBJECT_IDENTIFIER = 0x06; + private const ASN1_SEQUENCE = 0x10; // also defined in JWT + private const ASN1_BIT_STRING = 0x03; + private const EC_CURVES = [ + 'P-256' => '1.2.840.10045.3.1.7', // Len: 64 + 'secp256k1' => '1.3.132.0.10', // Len: 64 + 'P-384' => '1.3.132.0.34', // Len: 96 + // 'P-521' => '1.3.132.0.35', // Len: 132 (not supported) + ]; + + // For keys with "kty" equal to "OKP" (Octet Key Pair), the "crv" parameter must contain the key subtype. + // This library supports the following subtypes: + private const OKP_SUBTYPES = [ + 'Ed25519' => true, // RFC 8037 + ]; + + /** + * Parse a set of JWK keys + * + * @param array $jwks The JSON Web Key Set as an associative array + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return array An associative array of key IDs (kid) to Key objects + * + * @throws InvalidArgumentException Provided JWK Set is empty + * @throws UnexpectedValueException Provided JWK Set was invalid + * @throws DomainException OpenSSL failure + * + * @uses parseKey + */ + public static function parseKeySet(array $jwks, string $defaultAlg = null): array + { + $keys = []; + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + if ($key = self::parseKey($v, $defaultAlg)) { + $keys[(string) $kid] = $key; + } + } + + if (0 === \count($keys)) { + throw new UnexpectedValueException('No supported algorithms found in JWK Set'); + } + + return $keys; + } + + /** + * Parse a JWK key + * + * @param array $jwk An individual JWK + * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the + * JSON Web Key Set + * + * @return Key The key object for the JWK + * + * @throws InvalidArgumentException Provided JWK is empty + * @throws UnexpectedValueException Provided JWK was invalid + * @throws DomainException OpenSSL failure + * + * @uses createPemFromModulusAndExponent + */ + public static function parseKey(array $jwk, string $defaultAlg = null): ?Key + { + if (empty($jwk)) { + throw new InvalidArgumentException('JWK must not be empty'); + } + + if (!isset($jwk['kty'])) { + throw new UnexpectedValueException('JWK must contain a "kty" parameter'); + } + + if (!isset($jwk['alg'])) { + if (\is_null($defaultAlg)) { + // The "alg" parameter is optional in a KTY, but an algorithm is required + // for parsing in this library. Use the $defaultAlg parameter when parsing the + // key set in order to prevent this error. + // @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4 + throw new UnexpectedValueException('JWK must contain an "alg" parameter'); + } + $jwk['alg'] = $defaultAlg; + } + + switch ($jwk['kty']) { + case 'RSA': + if (!empty($jwk['d'])) { + throw new UnexpectedValueException('RSA private keys are not supported'); + } + if (!isset($jwk['n']) || !isset($jwk['e'])) { + throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"'); + } + + $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']); + $publicKey = \openssl_pkey_get_public($pem); + if (false === $publicKey) { + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + } + return new Key($publicKey, $jwk['alg']); + case 'EC': + if (isset($jwk['d'])) { + // The key is actually a private key + throw new UnexpectedValueException('Key data must be for a public key'); + } + + if (empty($jwk['crv'])) { + throw new UnexpectedValueException('crv not set'); + } + + if (!isset(self::EC_CURVES[$jwk['crv']])) { + throw new DomainException('Unrecognised or unsupported EC curve'); + } + + if (empty($jwk['x']) || empty($jwk['y'])) { + throw new UnexpectedValueException('x and y not set'); + } + + $publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']); + return new Key($publicKey, $jwk['alg']); + case 'OKP': + if (isset($jwk['d'])) { + // The key is actually a private key + throw new UnexpectedValueException('Key data must be for a public key'); + } + + if (!isset($jwk['crv'])) { + throw new UnexpectedValueException('crv not set'); + } + + if (empty(self::OKP_SUBTYPES[$jwk['crv']])) { + throw new DomainException('Unrecognised or unsupported OKP key subtype'); + } + + if (empty($jwk['x'])) { + throw new UnexpectedValueException('x not set'); + } + + // This library works internally with EdDSA keys (Ed25519) encoded in standard base64. + $publicKey = JWT::convertBase64urlToBase64($jwk['x']); + return new Key($publicKey, $jwk['alg']); + default: + break; + } + + return null; + } + + /** + * Converts the EC JWK values to pem format. + * + * @param string $crv The EC curve (only P-256 & P-384 is supported) + * @param string $x The EC x-coordinate + * @param string $y The EC y-coordinate + * + * @return string + */ + private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string + { + $pem = + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::OID) + ) + . self::encodeDER( + self::ASN1_OBJECT_IDENTIFIER, + self::encodeOID(self::EC_CURVES[$crv]) + ) + ) . + self::encodeDER( + self::ASN1_BIT_STRING, + \chr(0x00) . \chr(0x04) + . JWT::urlsafeB64Decode($x) + . JWT::urlsafeB64Decode($y) + ) + ); + + return sprintf( + "-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", + wordwrap(base64_encode($pem), 64, "\n", true) + ); + } + + /** + * Create a public key represented in PEM format from RSA modulus and exponent information + * + * @param string $n The RSA modulus encoded in Base64 + * @param string $e The RSA exponent encoded in Base64 + * + * @return string The RSA public key represented in PEM format + * + * @uses encodeLength + */ + private static function createPemFromModulusAndExponent( + string $n, + string $e + ): string { + $mod = JWT::urlsafeB64Decode($n); + $exp = JWT::urlsafeB64Decode($e); + + $modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod); + $publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp); + + $rsaPublicKey = \pack( + 'Ca*a*a*', + 48, + self::encodeLength(\strlen($modulus) + \strlen($publicExponent)), + $modulus, + $publicExponent + ); + + // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. + $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $rsaPublicKey = \chr(0) . $rsaPublicKey; + $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey; + + $rsaPublicKey = \pack( + 'Ca*a*', + 48, + self::encodeLength(\strlen($rsaOID . $rsaPublicKey)), + $rsaOID . $rsaPublicKey + ); + + return "-----BEGIN PUBLIC KEY-----\r\n" . + \chunk_split(\base64_encode($rsaPublicKey), 64) . + '-----END PUBLIC KEY-----'; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @param int $length + * @return string + */ + private static function encodeLength(int $length): string + { + if ($length <= 0x7F) { + return \chr($length); + } + + $temp = \ltrim(\pack('N', $length), \chr(0)); + + return \pack('Ca*', 0x80 | \strlen($temp), $temp); + } + + /** + * Encodes a value into a DER object. + * Also defined in Firebase\JWT\JWT + * + * @param int $type DER tag + * @param string $value the value to encode + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes a string into a DER-encoded OID. + * + * @param string $oid the OID string + * @return string the binary DER-encoded OID + */ + private static function encodeOID(string $oid): string + { + $octets = explode('.', $oid); + + // Get the first octet + $first = (int) array_shift($octets); + $second = (int) array_shift($octets); + $oid = \chr($first * 40 + $second); + + // Iterate over subsequent octets + foreach ($octets as $octet) { + if ($octet == 0) { + $oid .= \chr(0x00); + continue; + } + $bin = ''; + + while ($octet) { + $bin .= \chr(0x80 | ($octet & 0x7f)); + $octet >>= 7; + } + $bin[0] = $bin[0] & \chr(0x7f); + + // Convert to big endian if necessary + if (pack('V', 65534) == pack('L', 65534)) { + $oid .= strrev($bin); + } else { + $oid .= $bin; + } + } + + return $oid; + } +} diff --git a/vendor/firebase/php-jwt/src/JWT.php b/vendor/firebase/php-jwt/src/JWT.php new file mode 100644 index 0000000..2634920 --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWT.php @@ -0,0 +1,669 @@ + + * @author Anant Narayanan + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWT +{ + private const ASN1_INTEGER = 0x02; + private const ASN1_SEQUENCE = 0x10; + private const ASN1_BIT_STRING = 0x03; + + /** + * When checking nbf, iat or expiration times, + * we want to provide some extra leeway time to + * account for clock skew. + * + * @var int + */ + public static $leeway = 0; + + /** + * Allow the current timestamp to be specified. + * Useful for fixing a value within unit testing. + * Will default to PHP time() value if null. + * + * @var ?int + */ + public static $timestamp = null; + + /** + * @var array + */ + public static $supported_algs = [ + 'ES384' => ['openssl', 'SHA384'], + 'ES256' => ['openssl', 'SHA256'], + 'ES256K' => ['openssl', 'SHA256'], + 'HS256' => ['hash_hmac', 'SHA256'], + 'HS384' => ['hash_hmac', 'SHA384'], + 'HS512' => ['hash_hmac', 'SHA512'], + 'RS256' => ['openssl', 'SHA256'], + 'RS384' => ['openssl', 'SHA384'], + 'RS512' => ['openssl', 'SHA512'], + 'EdDSA' => ['sodium_crypto', 'EdDSA'], + ]; + + /** + * Decodes a JWT string into a PHP object. + * + * @param string $jwt The JWT + * @param Key|ArrayAccess|array $keyOrKeyArray The Key or associative array of key IDs + * (kid) to Key objects. + * If the algorithm used is asymmetric, this is + * the public key. + * Each Key object contains an algorithm and + * matching key. + * Supported algorithms are 'ES384','ES256', + * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384' + * and 'RS512'. + * @param stdClass $headers Optional. Populates stdClass with headers. + * + * @return stdClass The JWT's payload as a PHP object + * + * @throws InvalidArgumentException Provided key/key-array was empty or malformed + * @throws DomainException Provided JWT is malformed + * @throws UnexpectedValueException Provided JWT was invalid + * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed + * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' + * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' + * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode( + string $jwt, + $keyOrKeyArray, + stdClass &$headers = null + ): stdClass { + // Validate JWT + $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; + + if (empty($keyOrKeyArray)) { + throw new InvalidArgumentException('Key may not be empty'); + } + $tks = \explode('.', $jwt); + if (\count($tks) !== 3) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + $headerRaw = static::urlsafeB64Decode($headb64); + if (null === ($header = static::jsonDecode($headerRaw))) { + throw new UnexpectedValueException('Invalid header encoding'); + } + if ($headers !== null) { + $headers = $header; + } + $payloadRaw = static::urlsafeB64Decode($bodyb64); + if (null === ($payload = static::jsonDecode($payloadRaw))) { + throw new UnexpectedValueException('Invalid claims encoding'); + } + if (\is_array($payload)) { + // prevent PHP Fatal Error in edge-cases when payload is empty array + $payload = (object) $payload; + } + if (!$payload instanceof stdClass) { + throw new UnexpectedValueException('Payload must be a JSON object'); + } + $sig = static::urlsafeB64Decode($cryptob64); + if (empty($header->alg)) { + throw new UnexpectedValueException('Empty algorithm'); + } + if (empty(static::$supported_algs[$header->alg])) { + throw new UnexpectedValueException('Algorithm not supported'); + } + + $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null); + + // Check the algorithm + if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } + if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) { + // OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures + $sig = self::signatureToDER($sig); + } + if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) { + throw new SignatureInvalidException('Signature verification failed'); + } + + // Check the nbf if it is defined. This is the time that the + // token can actually be used. If it's not yet that time, abort. + if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) { + $ex = new BeforeValidException( + 'Cannot handle token with nbf prior to ' . \date(DateTime::ISO8601, (int) $payload->nbf) + ); + $ex->setPayload($payload); + throw $ex; + } + + // Check that this token has been created before 'now'. This prevents + // using tokens that have been created for later use (and haven't + // correctly used the nbf claim). + if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) { + $ex = new BeforeValidException( + 'Cannot handle token with iat prior to ' . \date(DateTime::ISO8601, (int) $payload->iat) + ); + $ex->setPayload($payload); + throw $ex; + } + + // Check if this token has expired. + if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { + $ex = new ExpiredException('Expired token'); + $ex->setPayload($payload); + throw $ex; + } + + return $payload; + } + + /** + * Converts and signs a PHP array into a JWT string. + * + * @param array $payload PHP array + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' + * @param string $keyId + * @param array $head An array with header elements to attach + * + * @return string A signed JWT + * + * @uses jsonEncode + * @uses urlsafeB64Encode + */ + public static function encode( + array $payload, + $key, + string $alg, + string $keyId = null, + array $head = null + ): string { + $header = ['typ' => 'JWT']; + if (isset($head) && \is_array($head)) { + $header = \array_merge($header, $head); + } + $header['alg'] = $alg; + if ($keyId !== null) { + $header['kid'] = $keyId; + } + $segments = []; + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header)); + $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload)); + $signing_input = \implode('.', $segments); + + $signature = static::sign($signing_input, $key, $alg); + $segments[] = static::urlsafeB64Encode($signature); + + return \implode('.', $segments); + } + + /** + * Sign a string with a given key and algorithm. + * + * @param string $msg The message to sign + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. + * @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256', + * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' + * + * @return string An encrypted message + * + * @throws DomainException Unsupported algorithm or bad key was specified + */ + public static function sign( + string $msg, + $key, + string $alg + ): string { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'hash_hmac': + if (!\is_string($key)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + return \hash_hmac($algorithm, $msg, $key, true); + case 'openssl': + $signature = ''; + $success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line + if (!$success) { + throw new DomainException('OpenSSL unable to sign data'); + } + if ($alg === 'ES256' || $alg === 'ES256K') { + $signature = self::signatureFromDER($signature, 256); + } elseif ($alg === 'ES384') { + $signature = self::signatureFromDER($signature, 384); + } + return $signature; + case 'sodium_crypto': + if (!\function_exists('sodium_crypto_sign_detached')) { + throw new DomainException('libsodium is not available'); + } + if (!\is_string($key)) { + throw new InvalidArgumentException('key must be a string when using EdDSA'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $key)); + $key = base64_decode((string) end($lines)); + if (\strlen($key) === 0) { + throw new DomainException('Key cannot be empty string'); + } + return sodium_crypto_sign_detached($msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + } + + throw new DomainException('Algorithm not supported'); + } + + /** + * Verify a signature with the message, key and method. Not all methods + * are symmetric, so we must have a separate verify and sign method. + * + * @param string $msg The original message (header and body) + * @param string $signature The original signature + * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey + * @param string $alg The algorithm + * + * @return bool + * + * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure + */ + private static function verify( + string $msg, + string $signature, + $keyMaterial, + string $alg + ): bool { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'openssl': + $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line + if ($success === 1) { + return true; + } + if ($success === 0) { + return false; + } + // returns 1 on success, 0 on failure, -1 on error. + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + case 'sodium_crypto': + if (!\function_exists('sodium_crypto_sign_verify_detached')) { + throw new DomainException('libsodium is not available'); + } + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using EdDSA'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $keyMaterial)); + $key = base64_decode((string) end($lines)); + if (\strlen($key) === 0) { + throw new DomainException('Key cannot be empty string'); + } + if (\strlen($signature) === 0) { + throw new DomainException('Signature cannot be empty string'); + } + return sodium_crypto_sign_verify_detached($signature, $msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + case 'hash_hmac': + default: + if (!\is_string($keyMaterial)) { + throw new InvalidArgumentException('key must be a string when using hmac'); + } + $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true); + return self::constantTimeEquals($hash, $signature); + } + } + + /** + * Decode a JSON string into a PHP object. + * + * @param string $input JSON string + * + * @return mixed The decoded JSON string + * + * @throws DomainException Provided string was invalid JSON + */ + public static function jsonDecode(string $input) + { + $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING); + + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($obj === null && $input !== 'null') { + throw new DomainException('Null result with non-null input'); + } + return $obj; + } + + /** + * Encode a PHP array into a JSON string. + * + * @param array $input A PHP array + * + * @return string JSON representation of the PHP array + * + * @throws DomainException Provided object could not be encoded to valid JSON + */ + public static function jsonEncode(array $input): string + { + if (PHP_VERSION_ID >= 50400) { + $json = \json_encode($input, \JSON_UNESCAPED_SLASHES); + } else { + // PHP 5.3 only + $json = \json_encode($input); + } + if ($errno = \json_last_error()) { + self::handleJsonError($errno); + } elseif ($json === 'null') { + throw new DomainException('Null result with non-null input'); + } + if ($json === false) { + throw new DomainException('Provided object could not be encoded to valid JSON'); + } + return $json; + } + + /** + * Decode a string with URL-safe Base64. + * + * @param string $input A Base64 encoded string + * + * @return string A decoded string + * + * @throws InvalidArgumentException invalid base64 characters + */ + public static function urlsafeB64Decode(string $input): string + { + return \base64_decode(self::convertBase64UrlToBase64($input)); + } + + /** + * Convert a string in the base64url (URL-safe Base64) encoding to standard base64. + * + * @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding) + * + * @return string A Base64 encoded string with standard characters (+/) and padding (=), when + * needed. + * + * @see https://www.rfc-editor.org/rfc/rfc4648 + */ + public static function convertBase64UrlToBase64(string $input): string + { + $remainder = \strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= \str_repeat('=', $padlen); + } + return \strtr($input, '-_', '+/'); + } + + /** + * Encode a string with URL-safe Base64. + * + * @param string $input The string you want encoded + * + * @return string The base64 encode of what you passed in + */ + public static function urlsafeB64Encode(string $input): string + { + return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); + } + + + /** + * Determine if an algorithm has been provided for each Key + * + * @param Key|ArrayAccess|array $keyOrKeyArray + * @param string|null $kid + * + * @throws UnexpectedValueException + * + * @return Key + */ + private static function getKey( + $keyOrKeyArray, + ?string $kid + ): Key { + if ($keyOrKeyArray instanceof Key) { + return $keyOrKeyArray; + } + + if (empty($kid) && $kid !== '0') { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + + if ($keyOrKeyArray instanceof CachedKeySet) { + // Skip "isset" check, as this will automatically refresh if not set + return $keyOrKeyArray[$kid]; + } + + if (!isset($keyOrKeyArray[$kid])) { + throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); + } + + return $keyOrKeyArray[$kid]; + } + + /** + * @param string $left The string of known length to compare against + * @param string $right The user-supplied string + * @return bool + */ + public static function constantTimeEquals(string $left, string $right): bool + { + if (\function_exists('hash_equals')) { + return \hash_equals($left, $right); + } + $len = \min(self::safeStrlen($left), self::safeStrlen($right)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (\ord($left[$i]) ^ \ord($right[$i])); + } + $status |= (self::safeStrlen($left) ^ self::safeStrlen($right)); + + return ($status === 0); + } + + /** + * Helper method to create a JSON error. + * + * @param int $errno An error number from json_last_error() + * + * @throws DomainException + * + * @return void + */ + private static function handleJsonError(int $errno): void + { + $messages = [ + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3 + ]; + throw new DomainException( + isset($messages[$errno]) + ? $messages[$errno] + : 'Unknown JSON error: ' . $errno + ); + } + + /** + * Get the number of bytes in cryptographic strings. + * + * @param string $str + * + * @return int + */ + private static function safeStrlen(string $str): int + { + if (\function_exists('mb_strlen')) { + return \mb_strlen($str, '8bit'); + } + return \strlen($str); + } + + /** + * Convert an ECDSA signature to an ASN.1 DER sequence + * + * @param string $sig The ECDSA signature to convert + * @return string The encoded DER object + */ + private static function signatureToDER(string $sig): string + { + // Separate the signature into r-value and s-value + $length = max(1, (int) (\strlen($sig) / 2)); + list($r, $s) = \str_split($sig, $length); + + // Trim leading zeros + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Convert r-value and s-value from unsigned big-endian integers to + // signed two's complement + if (\ord($r[0]) > 0x7f) { + $r = "\x00" . $r; + } + if (\ord($s[0]) > 0x7f) { + $s = "\x00" . $s; + } + + return self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER(self::ASN1_INTEGER, $r) . + self::encodeDER(self::ASN1_INTEGER, $s) + ); + } + + /** + * Encodes a value into a DER object. + * + * @param int $type DER tag + * @param string $value the value to encode + * + * @return string the encoded object + */ + private static function encodeDER(int $type, string $value): string + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes signature from a DER object. + * + * @param string $der binary signature in DER format + * @param int $keySize the number of bits in the key + * + * @return string the signature + */ + private static function signatureFromDER(string $der, int $keySize): string + { + // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE + list($offset, $_) = self::readDER($der); + list($offset, $r) = self::readDER($der, $offset); + list($offset, $s) = self::readDER($der, $offset); + + // Convert r-value and s-value from signed two's compliment to unsigned + // big-endian integers + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Pad out r and s so that they are $keySize bits long + $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT); + $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT); + + return $r . $s; + } + + /** + * Reads binary DER-encoded data and decodes into a single object + * + * @param string $der the binary data in DER format + * @param int $offset the offset of the data stream containing the object + * to decode + * + * @return array{int, string|null} the new offset and the decoded object + */ + private static function readDER(string $der, int $offset = 0): array + { + $pos = $offset; + $size = \strlen($der); + $constructed = (\ord($der[$pos]) >> 5) & 0x01; + $type = \ord($der[$pos++]) & 0x1f; + + // Length + $len = \ord($der[$pos++]); + if ($len & 0x80) { + $n = $len & 0x1f; + $len = 0; + while ($n-- && $pos < $size) { + $len = ($len << 8) | \ord($der[$pos++]); + } + } + + // Value + if ($type === self::ASN1_BIT_STRING) { + $pos++; // Skip the first contents octet (padding indicator) + $data = \substr($der, $pos, $len - 1); + $pos += $len - 1; + } elseif (!$constructed) { + $data = \substr($der, $pos, $len); + $pos += $len; + } else { + $data = null; + } + + return [$pos, $data]; + } +} diff --git a/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php b/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php new file mode 100644 index 0000000..7933ed6 --- /dev/null +++ b/vendor/firebase/php-jwt/src/JWTExceptionWithPayloadInterface.php @@ -0,0 +1,20 @@ +keyMaterial = $keyMaterial; + $this->algorithm = $algorithm; + } + + /** + * Return the algorithm valid for this key + * + * @return string + */ + public function getAlgorithm(): string + { + return $this->algorithm; + } + + /** + * @return string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } +} diff --git a/vendor/firebase/php-jwt/src/SignatureInvalidException.php b/vendor/firebase/php-jwt/src/SignatureInvalidException.php new file mode 100644 index 0000000..d35dee9 --- /dev/null +++ b/vendor/firebase/php-jwt/src/SignatureInvalidException.php @@ -0,0 +1,7 @@ + +
Homepage
http://www.github.com/google/google-auth-library-php
+
Reference Docs
https://googleapis.github.io/google-auth-library-php/main/
+
Authors
+
Tim Emiola
+
Stanley Cheung
+
Brent Shaffer
+
Copyright
Copyright © 2015 Google, Inc.
+
License
Apache 2.0
+ + +## Description + +This is Google's officially supported PHP client library for using OAuth 2.0 +authorization and authentication with Google APIs. + +### Installing via Composer + +The recommended way to install the google auth library is through +[Composer](http://getcomposer.org). + +```bash +# Install Composer +curl -sS https://getcomposer.org/installer | php +``` + +Next, run the Composer command to install the latest stable version: + +```bash +composer.phar require google/auth +``` + +## Application Default Credentials + +This library provides an implementation of +[Application Default Credentials (ADC)][application default credentials] for PHP. + +Application Default Credentials provides a simple way to get authorization +credentials for use in calling Google APIs, and is +the recommended approach to authorize calls to Cloud APIs. + +### Set up ADC + +To use ADC, you must set it up by providing credentials. +How you set up ADC depends on the environment where your code is running, +and whether you are running code in a test or production environment. + +For more information, see [Set up Application Default Credentials][set-up-adc]. + +### Enable the API you want to use + +Before making your API call, you must be sure the API you're calling has been +enabled. Go to **APIs & Auth** > **APIs** in the +[Google Developers Console][developer console] and enable the APIs you'd like to +call. For the example below, you must enable the `Drive API`. + +### Call the APIs + +As long as you update the environment variable below to point to *your* JSON +credentials file, the following code should output a list of your Drive files. + +```php +use Google\Auth\ApplicationDefaultCredentials; +use GuzzleHttp\Client; +use GuzzleHttp\HandlerStack; + +// specify the path to your application credentials +putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); + +// define the scopes for your API call +$scopes = ['https://www.googleapis.com/auth/drive.readonly']; + +// create middleware +$middleware = ApplicationDefaultCredentials::getMiddleware($scopes); +$stack = HandlerStack::create(); +$stack->push($middleware); + +// create the HTTP client +$client = new Client([ + 'handler' => $stack, + 'base_uri' => 'https://www.googleapis.com', + 'auth' => 'google_auth' // authorize all requests +]); + +// make the request +$response = $client->get('drive/v2/files'); + +// show the result! +print_r((string) $response->getBody()); +``` + +##### Guzzle 5 Compatibility + +If you are using [Guzzle 5][Guzzle 5], replace the `create middleware` and +`create the HTTP Client` steps with the following: + +```php +// create the HTTP client +$client = new Client([ + 'base_url' => 'https://www.googleapis.com', + 'auth' => 'google_auth' // authorize all requests +]); + +// create subscriber +$subscriber = ApplicationDefaultCredentials::getSubscriber($scopes); +$client->getEmitter()->attach($subscriber); +``` + +#### Call using an ID Token +If your application is running behind Cloud Run, or using Cloud Identity-Aware +Proxy (IAP), you will need to fetch an ID token to access your application. For +this, use the static method `getIdTokenMiddleware` on +`ApplicationDefaultCredentials`. + +```php +use Google\Auth\ApplicationDefaultCredentials; +use GuzzleHttp\Client; +use GuzzleHttp\HandlerStack; + +// specify the path to your application credentials +putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); + +// Provide the ID token audience. This can be a Client ID associated with an IAP application, +// Or the URL associated with a CloudRun App +// $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com'; +// $targetAudience = 'https://service-1234-uc.a.run.app'; +$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE'; + +// create middleware +$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience); +$stack = HandlerStack::create(); +$stack->push($middleware); + +// create the HTTP client +$client = new Client([ + 'handler' => $stack, + 'auth' => 'google_auth', + // Cloud Run, IAP, or custom resource URL + 'base_uri' => 'https://YOUR_PROTECTED_RESOURCE', +]); + +// make the request +$response = $client->get('/'); + +// show the result! +print_r((string) $response->getBody()); +``` + +For invoking Cloud Run services, your service account will need the +[`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service) +IAM permission. + +For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID +used when you set up your protected resource as the target audience. See how to +[secure your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto). + +#### Call using a specific JSON key +If you want to use a specific JSON key instead of using `GOOGLE_APPLICATION_CREDENTIALS` environment variable, you can + do this: + +```php +use Google\Auth\CredentialsLoader; +use Google\Auth\Middleware\AuthTokenMiddleware; +use GuzzleHttp\Client; +use GuzzleHttp\HandlerStack; + +// Define the Google Application Credentials array +$jsonKey = ['key' => 'value']; + +// define the scopes for your API call +$scopes = ['https://www.googleapis.com/auth/drive.readonly']; + +// Load credentials +$creds = CredentialsLoader::makeCredentials($scopes, $jsonKey); + +// optional caching +// $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache); + +// create middleware +$middleware = new AuthTokenMiddleware($creds); +$stack = HandlerStack::create(); +$stack->push($middleware); + +// create the HTTP client +$client = new Client([ + 'handler' => $stack, + 'base_uri' => 'https://www.googleapis.com', + 'auth' => 'google_auth' // authorize all requests +]); + +// make the request +$response = $client->get('drive/v2/files'); + +// show the result! +print_r((string) $response->getBody()); + +``` + +#### Call using Proxy-Authorization Header +If your application is behind a proxy such as [Google Cloud IAP][iap-proxy-header], +and your application occupies the `Authorization` request header, +you can include the ID token in a `Proxy-Authorization: Bearer` +header instead. If a valid ID token is found in a `Proxy-Authorization` header, +IAP authorizes the request with it. After authorizing the request, IAP passes +the Authorization header to your application without processing the content. +For this, use the static method `getProxyIdTokenMiddleware` on +`ApplicationDefaultCredentials`. + +```php +use Google\Auth\ApplicationDefaultCredentials; +use GuzzleHttp\Client; +use GuzzleHttp\HandlerStack; + +// specify the path to your application credentials +putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); + +// Provide the ID token audience. This can be a Client ID associated with an IAP application +// $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com'; +$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE'; + +// create middleware +$middleware = ApplicationDefaultCredentials::getProxyIdTokenMiddleware($targetAudience); +$stack = HandlerStack::create(); +$stack->push($middleware); + +// create the HTTP client +$client = new Client([ + 'handler' => $stack, + 'auth' => ['username', 'pass'], // auth option handled by your application + 'proxy_auth' => 'google_auth', +]); + +// make the request +$response = $client->get('/'); + +// show the result! +print_r((string) $response->getBody()); +``` + +[iap-proxy-header]: https://cloud.google.com/iap/docs/authentication-howto#authenticating_from_proxy-authorization_header + +#### External credentials (Workload identity federation) + +Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), +Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). + +Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud +resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access +Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys. + +Follow the detailed instructions on how to +[Configure Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds). + +#### Verifying JWTs + +If you are [using Google ID tokens to authenticate users][google-id-tokens], use +the `Google\Auth\AccessToken` class to verify the ID token: + +```php +use Google\Auth\AccessToken; + +$auth = new AccessToken(); +$auth->verify($idToken); +``` + +If your app is running behind [Google Identity-Aware Proxy][iap-id-tokens] +(IAP), you can verify the ID token coming from the IAP server by pointing to the +appropriate certificate URL for IAP. This is because IAP signs the ID +tokens with a different key than the Google Identity service: + +```php +use Google\Auth\AccessToken; + +$auth = new AccessToken(); +$auth->verify($idToken, [ + 'certsLocation' => AccessToken::IAP_CERT_URL +]); +``` + +[google-id-tokens]: https://developers.google.com/identity/sign-in/web/backend-auth +[iap-id-tokens]: https://cloud.google.com/iap/docs/signed-headers-howto + +## License + +This library is licensed under Apache 2.0. Full license text is +available in [COPYING][copying]. + +## Contributing + +See [CONTRIBUTING][contributing]. + +## Support + +Please +[report bugs at the project on Github](https://github.com/google/google-auth-library-php/issues). Don't +hesitate to +[ask questions](http://stackoverflow.com/questions/tagged/google-auth-library-php) +about the client or APIs on [StackOverflow](http://stackoverflow.com). + +[google-apis-php-client]: https://github.com/google/google-api-php-client +[application default credentials]: https://cloud.google.com/docs/authentication/application-default-credentials +[contributing]: https://github.com/google/google-auth-library-php/tree/main/.github/CONTRIBUTING.md +[copying]: https://github.com/google/google-auth-library-php/tree/main/COPYING +[Guzzle]: https://github.com/guzzle/guzzle +[Guzzle 5]: http://docs.guzzlephp.org/en/5.3 +[developer console]: https://console.developers.google.com +[set-up-adc]: https://cloud.google.com/docs/authentication/provide-credentials-adc diff --git a/vendor/google/auth/SECURITY.md b/vendor/google/auth/SECURITY.md new file mode 100644 index 0000000..8b58ae9 --- /dev/null +++ b/vendor/google/auth/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. diff --git a/vendor/google/auth/VERSION b/vendor/google/auth/VERSION new file mode 100644 index 0000000..7aa332e --- /dev/null +++ b/vendor/google/auth/VERSION @@ -0,0 +1 @@ +1.33.0 diff --git a/vendor/google/auth/autoload.php b/vendor/google/auth/autoload.php new file mode 100644 index 0000000..1e13827 --- /dev/null +++ b/vendor/google/auth/autoload.php @@ -0,0 +1,34 @@ + 3) { + // Maximum class file path depth in this project is 3. + $classPath = array_slice($classPath, 0, 3); + } + $filePath = dirname(__FILE__) . '/src/' . implode('/', $classPath) . '.php'; + if (file_exists($filePath)) { + require_once $filePath; + } +} + +spl_autoload_register('oauth2client_php_autoload'); diff --git a/vendor/google/auth/composer.json b/vendor/google/auth/composer.json new file mode 100644 index 0000000..88a698d --- /dev/null +++ b/vendor/google/auth/composer.json @@ -0,0 +1,41 @@ +{ + "name": "google/auth", + "type": "library", + "description": "Google Auth Library for PHP", + "keywords": ["google", "oauth2", "authentication"], + "homepage": "http://github.com/google/google-auth-library-php", + "license": "Apache-2.0", + "support": { + "docs": "https://googleapis.github.io/google-auth-library-php/main/" + }, + "require": { + "php": "^7.4||^8.0", + "firebase/php-jwt": "^6.0", + "guzzlehttp/guzzle": "^6.5.8||^7.4.5", + "guzzlehttp/psr7": "^2.4.5", + "psr/http-message": "^1.1||^2.0", + "psr/cache": "^1.0||^2.0||^3.0" + }, + "require-dev": { + "guzzlehttp/promises": "^2.0", + "squizlabs/php_codesniffer": "^3.5", + "phpunit/phpunit": "^9.0.0", + "phpspec/prophecy-phpunit": "^2.0", + "sebastian/comparator": ">=1.2.3", + "phpseclib/phpseclib": "^3.0", + "kelvinmo/simplejwt": "0.7.1" + }, + "suggest": { + "phpseclib/phpseclib": "May be used in place of OpenSSL for signing strings or for token management. Please require version ^2." + }, + "autoload": { + "psr-4": { + "Google\\Auth\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Google\\Auth\\Tests\\": "tests" + } + } +} diff --git a/vendor/google/auth/src/AccessToken.php b/vendor/google/auth/src/AccessToken.php new file mode 100644 index 0000000..630b279 --- /dev/null +++ b/vendor/google/auth/src/AccessToken.php @@ -0,0 +1,473 @@ +httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + $this->cache = $cache ?: new MemoryCacheItemPool(); + } + + /** + * Verifies an id token and returns the authenticated apiLoginTicket. + * Throws an exception if the id token is not valid. + * The audience parameter can be used to control which id tokens are + * accepted. By default, the id token must have been issued to this OAuth2 client. + * + * @param string $token The JSON Web Token to be verified. + * @param array $options [optional] { + * Configuration options. + * @type string $audience The indended recipient of the token. + * @type string $issuer The intended issuer of the token. + * @type string $cacheKey The cache key of the cached certs. Defaults to + * the sha1 of $certsLocation if provided, otherwise is set to + * "federated_signon_certs_v3". + * @type string $certsLocation The location (remote or local) from which + * to retrieve certificates, if not cached. This value should only be + * provided in limited circumstances in which you are sure of the + * behavior. + * @type bool $throwException Whether the function should throw an + * exception if the verification fails. This is useful for + * determining the reason verification failed. + * } + * @return array|false the token payload, if successful, or false if not. + * @throws InvalidArgumentException If certs could not be retrieved from a local file. + * @throws InvalidArgumentException If received certs are in an invalid format. + * @throws InvalidArgumentException If the cert alg is not supported. + * @throws RuntimeException If certs could not be retrieved from a remote location. + * @throws UnexpectedValueException If the token issuer does not match. + * @throws UnexpectedValueException If the token audience does not match. + */ + public function verify($token, array $options = []) + { + $audience = $options['audience'] ?? null; + $issuer = $options['issuer'] ?? null; + $certsLocation = $options['certsLocation'] ?? self::FEDERATED_SIGNON_CERT_URL; + $cacheKey = $options['cacheKey'] ?? $this->getCacheKeyFromCertLocation($certsLocation); + $throwException = $options['throwException'] ?? false; // for backwards compatibility + + // Check signature against each available cert. + $certs = $this->getCerts($certsLocation, $cacheKey, $options); + $alg = $this->determineAlg($certs); + if (!in_array($alg, ['RS256', 'ES256'])) { + throw new InvalidArgumentException( + 'unrecognized "alg" in certs, expected ES256 or RS256' + ); + } + try { + if ($alg == 'RS256') { + return $this->verifyRs256($token, $certs, $audience, $issuer); + } + return $this->verifyEs256($token, $certs, $audience, $issuer); + } catch (ExpiredException $e) { // firebase/php-jwt 5+ + } catch (SignatureInvalidException $e) { // firebase/php-jwt 5+ + } catch (InvalidTokenException $e) { // simplejwt + } catch (InvalidArgumentException $e) { + } catch (UnexpectedValueException $e) { + } + + if ($throwException) { + throw $e; + } + + return false; + } + + /** + * Identifies the expected algorithm to verify by looking at the "alg" key + * of the provided certs. + * + * @param array $certs Certificate array according to the JWK spec (see + * https://tools.ietf.org/html/rfc7517). + * @return string The expected algorithm, such as "ES256" or "RS256". + */ + private function determineAlg(array $certs) + { + $alg = null; + foreach ($certs as $cert) { + if (empty($cert['alg'])) { + throw new InvalidArgumentException( + 'certs expects "alg" to be set' + ); + } + $alg = $alg ?: $cert['alg']; + + if ($alg != $cert['alg']) { + throw new InvalidArgumentException( + 'More than one alg detected in certs' + ); + } + } + return $alg; + } + + /** + * Verifies an ES256-signed JWT. + * + * @param string $token The JSON Web Token to be verified. + * @param array $certs Certificate array according to the JWK spec (see + * https://tools.ietf.org/html/rfc7517). + * @param string|null $audience If set, returns false if the provided + * audience does not match the "aud" claim on the JWT. + * @param string|null $issuer If set, returns false if the provided + * issuer does not match the "iss" claim on the JWT. + * @return array the token payload, if successful, or false if not. + */ + private function verifyEs256($token, array $certs, $audience = null, $issuer = null) + { + $this->checkSimpleJwt(); + + $jwkset = new KeySet(); + foreach ($certs as $cert) { + $jwkset->add(KeyFactory::create($cert, 'php')); + } + + // Validate the signature using the key set and ES256 algorithm. + $jwt = $this->callSimpleJwtDecode([$token, $jwkset, 'ES256']); + $payload = $jwt->getClaims(); + + if ($audience) { + if (!isset($payload['aud']) || $payload['aud'] != $audience) { + throw new UnexpectedValueException('Audience does not match'); + } + } + + // @see https://cloud.google.com/iap/docs/signed-headers-howto#verifying_the_jwt_payload + $issuer = $issuer ?: self::IAP_ISSUER; + if (!isset($payload['iss']) || $payload['iss'] !== $issuer) { + throw new UnexpectedValueException('Issuer does not match'); + } + + return $payload; + } + + /** + * Verifies an RS256-signed JWT. + * + * @param string $token The JSON Web Token to be verified. + * @param array $certs Certificate array according to the JWK spec (see + * https://tools.ietf.org/html/rfc7517). + * @param string|null $audience If set, returns false if the provided + * audience does not match the "aud" claim on the JWT. + * @param string|null $issuer If set, returns false if the provided + * issuer does not match the "iss" claim on the JWT. + * @return array the token payload, if successful, or false if not. + */ + private function verifyRs256($token, array $certs, $audience = null, $issuer = null) + { + $this->checkAndInitializePhpsec(); + $keys = []; + foreach ($certs as $cert) { + if (empty($cert['kid'])) { + throw new InvalidArgumentException( + 'certs expects "kid" to be set' + ); + } + if (empty($cert['n']) || empty($cert['e'])) { + throw new InvalidArgumentException( + 'RSA certs expects "n" and "e" to be set' + ); + } + $publicKey = $this->loadPhpsecPublicKey($cert['n'], $cert['e']); + + // create an array of key IDs to certs for the JWT library + $keys[$cert['kid']] = new Key($publicKey, 'RS256'); + } + + $payload = $this->callJwtStatic('decode', [ + $token, + $keys, + ]); + + if ($audience) { + if (!property_exists($payload, 'aud') || $payload->aud != $audience) { + throw new UnexpectedValueException('Audience does not match'); + } + } + + // support HTTP and HTTPS issuers + // @see https://developers.google.com/identity/sign-in/web/backend-auth + $issuers = $issuer ? [$issuer] : [self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS]; + if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) { + throw new UnexpectedValueException('Issuer does not match'); + } + + return (array) $payload; + } + + /** + * Revoke an OAuth2 access token or refresh token. This method will revoke the current access + * token, if a token isn't provided. + * + * @param string|array $token The token (access token or a refresh token) that should be revoked. + * @param array $options [optional] Configuration options. + * @return bool Returns True if the revocation was successful, otherwise False. + */ + public function revoke($token, array $options = []) + { + if (is_array($token)) { + if (isset($token['refresh_token'])) { + $token = $token['refresh_token']; + } else { + $token = $token['access_token']; + } + } + + $body = Utils::streamFor(http_build_query(['token' => $token])); + $request = new Request('POST', self::OAUTH2_REVOKE_URI, [ + 'Cache-Control' => 'no-store', + 'Content-Type' => 'application/x-www-form-urlencoded', + ], $body); + + $httpHandler = $this->httpHandler; + + $response = $httpHandler($request, $options); + + return $response->getStatusCode() == 200; + } + + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are PEM encoded certificates. + * + * @param string $location The location from which to retrieve certs. + * @param string $cacheKey The key under which to cache the retrieved certs. + * @param array $options [optional] Configuration options. + * @return array + * @throws InvalidArgumentException If received certs are in an invalid format. + */ + private function getCerts($location, $cacheKey, array $options = []) + { + $cacheItem = $this->cache->getItem($cacheKey); + $certs = $cacheItem ? $cacheItem->get() : null; + + $expireTime = null; + if (!$certs) { + list($certs, $expireTime) = $this->retrieveCertsFromLocation($location, $options); + } + + if (!isset($certs['keys'])) { + if ($location !== self::IAP_CERT_URL) { + throw new InvalidArgumentException( + 'federated sign-on certs expects "keys" to be set' + ); + } + throw new InvalidArgumentException( + 'certs expects "keys" to be set' + ); + } + + // Push caching off until after verifying certs are in a valid format. + // Don't want to cache bad data. + if ($expireTime) { + $cacheItem->expiresAt(new DateTime($expireTime)); + $cacheItem->set($certs); + $this->cache->save($cacheItem); + } + + return $certs['keys']; + } + + /** + * Retrieve and cache a certificates file. + * + * @param string $url location + * @param array $options [optional] Configuration options. + * @return array{array, string} + * @throws InvalidArgumentException If certs could not be retrieved from a local file. + * @throws RuntimeException If certs could not be retrieved from a remote location. + */ + private function retrieveCertsFromLocation($url, array $options = []) + { + // If we're retrieving a local file, just grab it. + $expireTime = '+1 hour'; + if (strpos($url, 'http') !== 0) { + if (!file_exists($url)) { + throw new InvalidArgumentException(sprintf( + 'Failed to retrieve verification certificates from path: %s.', + $url + )); + } + + return [ + json_decode((string) file_get_contents($url), true), + $expireTime + ]; + } + + $httpHandler = $this->httpHandler; + $response = $httpHandler(new Request('GET', $url), $options); + + if ($response->getStatusCode() == 200) { + if ($cacheControl = $response->getHeaderLine('Cache-Control')) { + array_map(function ($value) use (&$expireTime) { + list($key, $value) = explode('=', $value) + [null, null]; + if (trim($key) == 'max-age') { + $expireTime = '+' . $value . ' seconds'; + } + }, explode(',', $cacheControl)); + } + return [ + json_decode((string) $response->getBody(), true), + $expireTime + ]; + } + + throw new RuntimeException(sprintf( + 'Failed to retrieve verification certificates: "%s".', + $response->getBody()->getContents() + ), $response->getStatusCode()); + } + + /** + * @return void + */ + private function checkAndInitializePhpsec() + { + if (!class_exists(RSA::class)) { + throw new RuntimeException('Please require phpseclib/phpseclib v3 to use this utility.'); + } + } + + /** + * @return string + * @throws TypeError If the key cannot be initialized to a string. + */ + private function loadPhpsecPublicKey(string $modulus, string $exponent): string + { + $key = PublicKeyLoader::load([ + 'n' => new BigInteger($this->callJwtStatic('urlsafeB64Decode', [ + $modulus, + ]), 256), + 'e' => new BigInteger($this->callJwtStatic('urlsafeB64Decode', [ + $exponent + ]), 256), + ]); + $formattedPublicKey = $key->toString('PKCS8'); + if (!is_string($formattedPublicKey)) { + throw new TypeError('Failed to initialize the key'); + } + return $formattedPublicKey; + } + + /** + * @return void + */ + private function checkSimpleJwt() + { + // @codeCoverageIgnoreStart + if (!class_exists(SimpleJwt::class)) { + throw new RuntimeException('Please require kelvinmo/simplejwt ^0.2 to use this utility.'); + } + // @codeCoverageIgnoreEnd + } + + /** + * Provide a hook to mock calls to the JWT static methods. + * + * @param string $method + * @param array $args + * @return mixed + */ + protected function callJwtStatic($method, array $args = []) + { + return call_user_func_array([JWT::class, $method], $args); // @phpstan-ignore-line + } + + /** + * Provide a hook to mock calls to the JWT static methods. + * + * @param array $args + * @return mixed + */ + protected function callSimpleJwtDecode(array $args = []) + { + return call_user_func_array([SimpleJwt::class, 'decode'], $args); + } + + /** + * Generate a cache key based on the cert location using sha1 with the + * exception of using "federated_signon_certs_v3" to preserve BC. + * + * @param string $certsLocation + * @return string + */ + private function getCacheKeyFromCertLocation($certsLocation) + { + $key = $certsLocation === self::FEDERATED_SIGNON_CERT_URL + ? 'federated_signon_certs_v3' + : sha1($certsLocation); + + return 'google_auth_certs_cache|' . $key; + } +} diff --git a/vendor/google/auth/src/ApplicationDefaultCredentials.php b/vendor/google/auth/src/ApplicationDefaultCredentials.php new file mode 100644 index 0000000..80437c8 --- /dev/null +++ b/vendor/google/auth/src/ApplicationDefaultCredentials.php @@ -0,0 +1,356 @@ +push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'auth' => 'google_auth' // authorize all requests + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + * ``` + */ +class ApplicationDefaultCredentials +{ + /** + * @deprecated + * + * Obtains an AuthTokenSubscriber that uses the default FetchAuthTokenInterface + * implementation to use in this environment. + * + * If supplied, $scope is used to in creating the credentials instance if + * this does not fallback to the compute engine defaults. + * + * @param string|string[] $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @return AuthTokenSubscriber + * @throws DomainException if no implementation can be obtained. + */ + public static function getSubscriber(// @phpstan-ignore-line + $scope = null, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache); + + /** @phpstan-ignore-next-line */ + return new AuthTokenSubscriber($creds, $httpHandler); + } + + /** + * Obtains an AuthTokenMiddleware that uses the default FetchAuthTokenInterface + * implementation to use in this environment. + * + * If supplied, $scope is used to in creating the credentials instance if + * this does not fallback to the compute engine defaults. + * + * @param string|string[] $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @param string $quotaProject specifies a project to bill for access + * charges associated with the request. + * @return AuthTokenMiddleware + * @throws DomainException if no implementation can be obtained. + */ + public static function getMiddleware( + $scope = null, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null, + $quotaProject = null + ) { + $creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache, $quotaProject); + + return new AuthTokenMiddleware($creds, $httpHandler); + } + + /** + * Obtains the default FetchAuthTokenInterface implementation to use + * in this environment. + * + * @param string|string[] $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @param string $quotaProject specifies a project to bill for access + * charges associated with the request. + * @param string|string[] $defaultScope The default scope to use if no + * user-defined scopes exist, expressed either as an Array or as a + * space-delimited string. + * @param string $universeDomain Specifies a universe domain to use for the + * calling client library + * + * @return FetchAuthTokenInterface + * @throws DomainException if no implementation can be obtained. + */ + public static function getCredentials( + $scope = null, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null, + $quotaProject = null, + $defaultScope = null, + string $universeDomain = null + ) { + $creds = null; + $jsonKey = CredentialsLoader::fromEnv() + ?: CredentialsLoader::fromWellKnownFile(); + $anyScope = $scope ?: $defaultScope; + + if (!$httpHandler) { + if (!($client = HttpClientCache::getHttpClient())) { + $client = new Client(); + HttpClientCache::setHttpClient($client); + } + + $httpHandler = HttpHandlerFactory::build($client); + } + + if (is_null($quotaProject)) { + // if a quota project isn't specified, try to get one from the env var + $quotaProject = CredentialsLoader::quotaProjectFromEnv(); + } + + if (!is_null($jsonKey)) { + if ($quotaProject) { + $jsonKey['quota_project_id'] = $quotaProject; + } + if ($universeDomain) { + $jsonKey['universe_domain'] = $universeDomain; + } + $creds = CredentialsLoader::makeCredentials( + $scope, + $jsonKey, + $defaultScope + ); + } elseif (AppIdentityCredentials::onAppEngine() && !GCECredentials::onAppEngineFlexible()) { + $creds = new AppIdentityCredentials($anyScope); + } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) { + $creds = new GCECredentials(null, $anyScope, null, $quotaProject, null, $universeDomain); + $creds->setIsOnGce(true); // save the credentials a trip to the metadata server + } + + if (is_null($creds)) { + throw new DomainException(self::notFound()); + } + if (!is_null($cache)) { + $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache); + } + return $creds; + } + + /** + * Obtains an AuthTokenMiddleware which will fetch an ID token to use in the + * Authorization header. The middleware is configured with the default + * FetchAuthTokenInterface implementation to use in this environment. + * + * If supplied, $targetAudience is used to set the "aud" on the resulting + * ID token. + * + * @param string $targetAudience The audience for the ID token. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @return AuthTokenMiddleware + * @throws DomainException if no implementation can be obtained. + */ + public static function getIdTokenMiddleware( + $targetAudience, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache); + + return new AuthTokenMiddleware($creds, $httpHandler); + } + + /** + * Obtains an ProxyAuthTokenMiddleware which will fetch an ID token to use in the + * Authorization header. The middleware is configured with the default + * FetchAuthTokenInterface implementation to use in this environment. + * + * If supplied, $targetAudience is used to set the "aud" on the resulting + * ID token. + * + * @param string $targetAudience The audience for the ID token. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @return ProxyAuthTokenMiddleware + * @throws DomainException if no implementation can be obtained. + */ + public static function getProxyIdTokenMiddleware( + $targetAudience, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $creds = self::getIdTokenCredentials($targetAudience, $httpHandler, $cacheConfig, $cache); + + return new ProxyAuthTokenMiddleware($creds, $httpHandler); + } + + /** + * Obtains the default FetchAuthTokenInterface implementation to use + * in this environment, configured with a $targetAudience for fetching an ID + * token. + * + * @param string $targetAudience The audience for the ID token. + * @param callable $httpHandler callback which delivers psr7 request + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache A cache implementation, may be + * provided if you have one already available for use. + * @return FetchAuthTokenInterface + * @throws DomainException if no implementation can be obtained. + * @throws InvalidArgumentException if JSON "type" key is invalid + */ + public static function getIdTokenCredentials( + $targetAudience, + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $creds = null; + $jsonKey = CredentialsLoader::fromEnv() + ?: CredentialsLoader::fromWellKnownFile(); + + if (!$httpHandler) { + if (!($client = HttpClientCache::getHttpClient())) { + $client = new Client(); + HttpClientCache::setHttpClient($client); + } + + $httpHandler = HttpHandlerFactory::build($client); + } + + if (!is_null($jsonKey)) { + if (!array_key_exists('type', $jsonKey)) { + throw new \InvalidArgumentException('json key is missing the type field'); + } + + if ($jsonKey['type'] == 'authorized_user') { + throw new InvalidArgumentException('ID tokens are not supported for end user credentials'); + } + + if ($jsonKey['type'] != 'service_account') { + throw new InvalidArgumentException('invalid value in the type field'); + } + + $creds = new ServiceAccountCredentials(null, $jsonKey, null, $targetAudience); + } elseif (self::onGce($httpHandler, $cacheConfig, $cache)) { + $creds = new GCECredentials(null, null, $targetAudience); + $creds->setIsOnGce(true); // save the credentials a trip to the metadata server + } + + if (is_null($creds)) { + throw new DomainException(self::notFound()); + } + if (!is_null($cache)) { + $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache); + } + return $creds; + } + + /** + * @return string + */ + private static function notFound() + { + $msg = 'Your default credentials were not found. To set up '; + $msg .= 'Application Default Credentials, see '; + $msg .= 'https://cloud.google.com/docs/authentication/external/set-up-adc'; + + return $msg; + } + + /** + * @param callable $httpHandler + * @param array $cacheConfig + * @param CacheItemPoolInterface $cache + * @return bool + */ + private static function onGce( + callable $httpHandler = null, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $gceCacheConfig = []; + foreach (['lifetime', 'prefix'] as $key) { + if (isset($cacheConfig['gce_' . $key])) { + $gceCacheConfig[$key] = $cacheConfig['gce_' . $key]; + } + } + + return (new GCECache($gceCacheConfig, $cache))->onGce($httpHandler); + } +} diff --git a/vendor/google/auth/src/Cache/InvalidArgumentException.php b/vendor/google/auth/src/Cache/InvalidArgumentException.php new file mode 100644 index 0000000..331e561 --- /dev/null +++ b/vendor/google/auth/src/Cache/InvalidArgumentException.php @@ -0,0 +1,24 @@ +key = $key; + } + + /** + * {@inheritdoc} + */ + public function getKey() + { + return $this->key; + } + + /** + * {@inheritdoc} + */ + public function get() + { + return $this->isHit() ? $this->value : null; + } + + /** + * {@inheritdoc} + */ + public function isHit() + { + if (!$this->isHit) { + return false; + } + + if ($this->expiration === null) { + return true; + } + + return $this->currentTime()->getTimestamp() < $this->expiration->getTimestamp(); + } + + /** + * {@inheritdoc} + */ + public function set($value) + { + $this->isHit = true; + $this->value = $value; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function expiresAt($expiration) + { + if ($this->isValidExpiration($expiration)) { + $this->expiration = $expiration; + + return $this; + } + + $error = sprintf( + 'Argument 1 passed to %s::expiresAt() must implement interface DateTimeInterface, %s given', + get_class($this), + gettype($expiration) + ); + + throw new TypeError($error); + } + + /** + * {@inheritdoc} + */ + public function expiresAfter($time) + { + if (is_int($time)) { + $this->expiration = $this->currentTime()->add(new \DateInterval("PT{$time}S")); + } elseif ($time instanceof \DateInterval) { + $this->expiration = $this->currentTime()->add($time); + } elseif ($time === null) { + $this->expiration = $time; + } else { + $message = 'Argument 1 passed to %s::expiresAfter() must be an ' . + 'instance of DateInterval or of the type integer, %s given'; + $error = sprintf($message, get_class($this), gettype($time)); + + throw new TypeError($error); + } + + return $this; + } + + /** + * Determines if an expiration is valid based on the rules defined by PSR6. + * + * @param mixed $expiration + * @return bool + */ + private function isValidExpiration($expiration) + { + if ($expiration === null) { + return true; + } + + if ($expiration instanceof DateTimeInterface) { + return true; + } + + return false; + } + + /** + * @return DateTime + */ + protected function currentTime() + { + return new DateTime('now', new DateTimeZone('UTC')); + } +} diff --git a/vendor/google/auth/src/Cache/MemoryCacheItemPool.php b/vendor/google/auth/src/Cache/MemoryCacheItemPool.php new file mode 100644 index 0000000..2c7a9d5 --- /dev/null +++ b/vendor/google/auth/src/Cache/MemoryCacheItemPool.php @@ -0,0 +1,183 @@ +getItems([$key])); // @phpstan-ignore-line + } + + /** + * {@inheritdoc} + * + * @return iterable + * A traversable collection of Cache Items keyed by the cache keys of + * each item. A Cache item will be returned for each key, even if that + * key is not found. However, if no keys are specified then an empty + * traversable MUST be returned instead. + */ + public function getItems(array $keys = []): iterable + { + $items = []; + $itemClass = \PHP_VERSION_ID >= 80000 ? TypedItem::class : Item::class; + foreach ($keys as $key) { + $items[$key] = $this->hasItem($key) ? clone $this->items[$key] : new $itemClass($key); + } + + return $items; + } + + /** + * {@inheritdoc} + * + * @return bool + * True if item exists in the cache, false otherwise. + */ + public function hasItem($key): bool + { + $this->isValidKey($key); + + return isset($this->items[$key]) && $this->items[$key]->isHit(); + } + + /** + * {@inheritdoc} + * + * @return bool + * True if the pool was successfully cleared. False if there was an error. + */ + public function clear(): bool + { + $this->items = []; + $this->deferredItems = []; + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + * True if the item was successfully removed. False if there was an error. + */ + public function deleteItem($key): bool + { + return $this->deleteItems([$key]); + } + + /** + * {@inheritdoc} + * + * @return bool + * True if the items were successfully removed. False if there was an error. + */ + public function deleteItems(array $keys): bool + { + array_walk($keys, [$this, 'isValidKey']); + + foreach ($keys as $key) { + unset($this->items[$key]); + } + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + * True if the item was successfully persisted. False if there was an error. + */ + public function save(CacheItemInterface $item): bool + { + $this->items[$item->getKey()] = $item; + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + * False if the item could not be queued or if a commit was attempted and failed. True otherwise. + */ + public function saveDeferred(CacheItemInterface $item): bool + { + $this->deferredItems[$item->getKey()] = $item; + + return true; + } + + /** + * {@inheritdoc} + * + * @return bool + * True if all not-yet-saved items were successfully saved or there were none. False otherwise. + */ + public function commit(): bool + { + foreach ($this->deferredItems as $item) { + $this->save($item); + } + + $this->deferredItems = []; + + return true; + } + + /** + * Determines if the provided key is valid. + * + * @param string $key + * @return bool + * @throws InvalidArgumentException + */ + private function isValidKey($key) + { + $invalidCharacters = '{}()/\\\\@:'; + + if (!is_string($key) || preg_match("#[$invalidCharacters]#", $key)) { + throw new InvalidArgumentException('The provided key is not valid: ' . var_export($key, true)); + } + + return true; + } +} diff --git a/vendor/google/auth/src/Cache/SysVCacheItemPool.php b/vendor/google/auth/src/Cache/SysVCacheItemPool.php new file mode 100644 index 0000000..39a8c30 --- /dev/null +++ b/vendor/google/auth/src/Cache/SysVCacheItemPool.php @@ -0,0 +1,249 @@ + + */ + private $options; + + /** + * @var bool + */ + private $hasLoadedItems = false; + + /** + * Create a SystemV shared memory based CacheItemPool. + * + * @param array $options { + * [optional] Configuration options. + * + * @type int $variableKey The variable key for getting the data from the shared memory. **Defaults to** 1. + * @type string $proj The project identifier for ftok. This needs to be a one character string. + * **Defaults to** 'A'. + * @type int $memsize The memory size in bytes for shm_attach. **Defaults to** 10000. + * @type int $perm The permission for shm_attach. **Defaults to** 0600. + * } + */ + public function __construct($options = []) + { + if (! extension_loaded('sysvshm')) { + throw new \RuntimeException( + 'sysvshm extension is required to use this ItemPool' + ); + } + $this->options = $options + [ + 'variableKey' => self::VAR_KEY, + 'proj' => self::DEFAULT_PROJ, + 'memsize' => self::DEFAULT_MEMSIZE, + 'perm' => self::DEFAULT_PERM + ]; + $this->items = []; + $this->deferredItems = []; + $this->sysvKey = ftok(__FILE__, $this->options['proj']); + } + + /** + * @param mixed $key + * @return CacheItemInterface + */ + public function getItem($key): CacheItemInterface + { + $this->loadItems(); + return current($this->getItems([$key])); // @phpstan-ignore-line + } + + /** + * @param array $keys + * @return iterable + */ + public function getItems(array $keys = []): iterable + { + $this->loadItems(); + $items = []; + $itemClass = \PHP_VERSION_ID >= 80000 ? TypedItem::class : Item::class; + foreach ($keys as $key) { + $items[$key] = $this->hasItem($key) ? + clone $this->items[$key] : + new $itemClass($key); + } + return $items; + } + + /** + * {@inheritdoc} + */ + public function hasItem($key): bool + { + $this->loadItems(); + return isset($this->items[$key]) && $this->items[$key]->isHit(); + } + + /** + * {@inheritdoc} + */ + public function clear(): bool + { + $this->items = []; + $this->deferredItems = []; + return $this->saveCurrentItems(); + } + + /** + * {@inheritdoc} + */ + public function deleteItem($key): bool + { + return $this->deleteItems([$key]); + } + + /** + * {@inheritdoc} + */ + public function deleteItems(array $keys): bool + { + if (!$this->hasLoadedItems) { + $this->loadItems(); + } + + foreach ($keys as $key) { + unset($this->items[$key]); + } + return $this->saveCurrentItems(); + } + + /** + * {@inheritdoc} + */ + public function save(CacheItemInterface $item): bool + { + if (!$this->hasLoadedItems) { + $this->loadItems(); + } + + $this->items[$item->getKey()] = $item; + return $this->saveCurrentItems(); + } + + /** + * {@inheritdoc} + */ + public function saveDeferred(CacheItemInterface $item): bool + { + $this->deferredItems[$item->getKey()] = $item; + return true; + } + + /** + * {@inheritdoc} + */ + public function commit(): bool + { + foreach ($this->deferredItems as $item) { + if ($this->save($item) === false) { + return false; + } + } + $this->deferredItems = []; + return true; + } + + /** + * Save the current items. + * + * @return bool true when success, false upon failure + */ + private function saveCurrentItems() + { + $shmid = shm_attach( + $this->sysvKey, + $this->options['memsize'], + $this->options['perm'] + ); + if ($shmid !== false) { + $ret = shm_put_var( + $shmid, + $this->options['variableKey'], + $this->items + ); + shm_detach($shmid); + return $ret; + } + return false; + } + + /** + * Load the items from the shared memory. + * + * @return bool true when success, false upon failure + */ + private function loadItems() + { + $shmid = shm_attach( + $this->sysvKey, + $this->options['memsize'], + $this->options['perm'] + ); + if ($shmid !== false) { + $data = @shm_get_var($shmid, $this->options['variableKey']); + if (!empty($data)) { + $this->items = $data; + } else { + $this->items = []; + } + shm_detach($shmid); + $this->hasLoadedItems = true; + return true; + } + return false; + } +} diff --git a/vendor/google/auth/src/Cache/TypedItem.php b/vendor/google/auth/src/Cache/TypedItem.php new file mode 100644 index 0000000..cce6740 --- /dev/null +++ b/vendor/google/auth/src/Cache/TypedItem.php @@ -0,0 +1,170 @@ +key = $key; + $this->expiration = null; + } + + /** + * {@inheritdoc} + */ + public function getKey(): string + { + return $this->key; + } + + /** + * {@inheritdoc} + */ + public function get(): mixed + { + return $this->isHit() ? $this->value : null; + } + + /** + * {@inheritdoc} + */ + public function isHit(): bool + { + if (!$this->isHit) { + return false; + } + + if ($this->expiration === null) { + return true; + } + + return $this->currentTime()->getTimestamp() < $this->expiration->getTimestamp(); + } + + /** + * {@inheritdoc} + */ + public function set(mixed $value): static + { + $this->isHit = true; + $this->value = $value; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function expiresAt($expiration): static + { + if ($this->isValidExpiration($expiration)) { + $this->expiration = $expiration; + + return $this; + } + + $error = sprintf( + 'Argument 1 passed to %s::expiresAt() must implement interface DateTimeInterface, %s given', + get_class($this), + gettype($expiration) + ); + + throw new \TypeError($error); + } + + /** + * {@inheritdoc} + */ + public function expiresAfter($time): static + { + if (is_int($time)) { + $this->expiration = $this->currentTime()->add(new \DateInterval("PT{$time}S")); + } elseif ($time instanceof \DateInterval) { + $this->expiration = $this->currentTime()->add($time); + } elseif ($time === null) { + $this->expiration = $time; + } else { + $message = 'Argument 1 passed to %s::expiresAfter() must be an ' . + 'instance of DateInterval or of the type integer, %s given'; + $error = sprintf($message, get_class($this), gettype($time)); + + throw new \TypeError($error); + } + + return $this; + } + + /** + * Determines if an expiration is valid based on the rules defined by PSR6. + * + * @param mixed $expiration + * @return bool + */ + private function isValidExpiration($expiration) + { + if ($expiration === null) { + return true; + } + + // We test for two types here due to the fact the DateTimeInterface + // was not introduced until PHP 5.5. Checking for the DateTime type as + // well allows us to support 5.4. + if ($expiration instanceof \DateTimeInterface) { + return true; + } + + return false; + } + + /** + * @return \DateTime + */ + protected function currentTime() + { + return new \DateTime('now', new \DateTimeZone('UTC')); + } +} diff --git a/vendor/google/auth/src/CacheTrait.php b/vendor/google/auth/src/CacheTrait.php new file mode 100644 index 0000000..2ef8290 --- /dev/null +++ b/vendor/google/auth/src/CacheTrait.php @@ -0,0 +1,110 @@ + + */ + private $cacheConfig; + + /** + * @var ?CacheItemPoolInterface + */ + private $cache; + + /** + * Gets the cached value if it is present in the cache when that is + * available. + * + * @param mixed $k + * + * @return mixed + */ + private function getCachedValue($k) + { + if (is_null($this->cache)) { + return null; + } + + $key = $this->getFullCacheKey($k); + if (is_null($key)) { + return null; + } + + $cacheItem = $this->cache->getItem($key); + if ($cacheItem->isHit()) { + return $cacheItem->get(); + } + } + + /** + * Saves the value in the cache when that is available. + * + * @param mixed $k + * @param mixed $v + * @return mixed + */ + private function setCachedValue($k, $v) + { + if (is_null($this->cache)) { + return null; + } + + $key = $this->getFullCacheKey($k); + if (is_null($key)) { + return null; + } + + $cacheItem = $this->cache->getItem($key); + $cacheItem->set($v); + $cacheItem->expiresAfter($this->cacheConfig['lifetime']); + return $this->cache->save($cacheItem); + } + + /** + * @param null|string $key + * @return null|string + */ + private function getFullCacheKey($key) + { + if (is_null($key)) { + return null; + } + + $key = $this->cacheConfig['prefix'] . $key; + + // ensure we do not have illegal characters + $key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key); + + // Hash keys if they exceed $maxKeyLength (defaults to 64) + if ($this->maxKeyLength && strlen($key) > $this->maxKeyLength) { + $key = substr(hash('sha256', $key), 0, $this->maxKeyLength); + } + + return $key; + } +} diff --git a/vendor/google/auth/src/CredentialSource/AwsNativeSource.php b/vendor/google/auth/src/CredentialSource/AwsNativeSource.php new file mode 100644 index 0000000..3a8c20e --- /dev/null +++ b/vendor/google/auth/src/CredentialSource/AwsNativeSource.php @@ -0,0 +1,360 @@ +audience = $audience; + $this->regionalCredVerificationUrl = $regionalCredVerificationUrl; + $this->regionUrl = $regionUrl; + $this->securityCredentialsUrl = $securityCredentialsUrl; + $this->imdsv2SessionTokenUrl = $imdsv2SessionTokenUrl; + } + + public function fetchSubjectToken(callable $httpHandler = null): string + { + if (is_null($httpHandler)) { + $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + + $headers = []; + if ($this->imdsv2SessionTokenUrl) { + $headers = [ + 'X-aws-ec2-metadata-token' => self::getImdsV2SessionToken($this->imdsv2SessionTokenUrl, $httpHandler) + ]; + } + + if (!$signingVars = self::getSigningVarsFromEnv()) { + if (!$this->securityCredentialsUrl) { + throw new \LogicException('Unable to get credentials from ENV, and no security credentials URL provided'); + } + $signingVars = self::getSigningVarsFromUrl( + $httpHandler, + $this->securityCredentialsUrl, + self::getRoleName($httpHandler, $this->securityCredentialsUrl, $headers), + $headers + ); + } + + if (!$region = self::getRegionFromEnv()) { + if (!$this->regionUrl) { + throw new \LogicException('Unable to get region from ENV, and no region URL provided'); + } + $region = self::getRegionFromUrl($httpHandler, $this->regionUrl, $headers); + } + $url = str_replace('{region}', $region, $this->regionalCredVerificationUrl); + $host = parse_url($url)['host'] ?? ''; + + // From here we use the signing vars to create the signed request to receive a token + [$accessKeyId, $secretAccessKey, $securityToken] = $signingVars; + $headers = self::getSignedRequestHeaders($region, $host, $accessKeyId, $secretAccessKey, $securityToken); + + // Inject x-goog-cloud-target-resource into header + $headers['x-goog-cloud-target-resource'] = $this->audience; + + // Format headers as they're expected in the subject token + $formattedHeaders= array_map( + fn ($k, $v) => ['key' => $k, 'value' => $v], + array_keys($headers), + $headers, + ); + + $request = [ + 'headers' => $formattedHeaders, + 'method' => 'POST', + 'url' => $url, + ]; + + return urlencode(json_encode($request) ?: ''); + } + + /** + * @internal + */ + public static function getImdsV2SessionToken(string $imdsV2Url, callable $httpHandler): string + { + $headers = [ + 'X-aws-ec2-metadata-token-ttl-seconds' => '21600' + ]; + $request = new Request( + 'PUT', + $imdsV2Url, + $headers + ); + + $response = $httpHandler($request); + return (string) $response->getBody(); + } + + /** + * @see http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + * + * @internal + * + * @return array + */ + public static function getSignedRequestHeaders( + string $region, + string $host, + string $accessKeyId, + string $secretAccessKey, + ?string $securityToken + ): array { + $service = 'sts'; + + # Create a date for headers and the credential string in ISO-8601 format + $amzdate = date('Ymd\THis\Z'); + $datestamp = date('Ymd'); # Date w/o time, used in credential scope + + # Create the canonical headers and signed headers. Header names + # must be trimmed and lowercase, and sorted in code point order from + # low to high. Note that there is a trailing \n. + $canonicalHeaders = sprintf("host:%s\nx-amz-date:%s\n", $host, $amzdate); + if ($securityToken) { + $canonicalHeaders .= sprintf("x-amz-security-token:%s\n", $securityToken); + } + + # Step 5: Create the list of signed headers. This lists the headers + # in the canonicalHeaders list, delimited with ";" and in alpha order. + # Note: The request can include any headers; $canonicalHeaders and + # $signedHeaders lists those that you want to be included in the + # hash of the request. "Host" and "x-amz-date" are always required. + $signedHeaders = 'host;x-amz-date'; + if ($securityToken) { + $signedHeaders .= ';x-amz-security-token'; + } + + # Step 6: Create payload hash (hash of the request body content). For GET + # requests, the payload is an empty string (""). + $payloadHash = hash('sha256', ''); + + # Step 7: Combine elements to create canonical request + $canonicalRequest = implode("\n", [ + 'POST', // method + '/', // canonical URL + self::CRED_VERIFICATION_QUERY, // query string + $canonicalHeaders, + $signedHeaders, + $payloadHash + ]); + + # ************* TASK 2: CREATE THE STRING TO SIGN************* + # Match the algorithm to the hashing algorithm you use, either SHA-1 or + # SHA-256 (recommended) + $algorithm = 'AWS4-HMAC-SHA256'; + $scope = implode('/', [$datestamp, $region, $service, 'aws4_request']); + $stringToSign = implode("\n", [$algorithm, $amzdate, $scope, hash('sha256', $canonicalRequest)]); + + # ************* TASK 3: CALCULATE THE SIGNATURE ************* + # Create the signing key using the function defined above. + // (done above) + $signingKey = self::getSignatureKey($secretAccessKey, $datestamp, $region, $service); + + # Sign the string_to_sign using the signing_key + $signature = bin2hex(self::hmacSign($signingKey, $stringToSign)); + + # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST ************* + # The signing information can be either in a query string value or in + # a header named Authorization. This code shows how to use a header. + # Create authorization header and add to request headers + $authorizationHeader = sprintf( + '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s', + $algorithm, + $accessKeyId, + $scope, + $signedHeaders, + $signature + ); + + # The request can include any headers, but MUST include "host", "x-amz-date", + # and (for this scenario) "Authorization". "host" and "x-amz-date" must + # be included in the canonical_headers and signed_headers, as noted + # earlier. Order here is not significant. + $headers = [ + 'host' => $host, + 'x-amz-date' => $amzdate, + 'Authorization' => $authorizationHeader, + ]; + if ($securityToken) { + $headers['x-amz-security-token'] = $securityToken; + } + + return $headers; + } + + /** + * @internal + */ + public static function getRegionFromEnv(): ?string + { + $region = getenv('AWS_REGION'); + if (empty($region)) { + $region = getenv('AWS_DEFAULT_REGION'); + } + return $region ?: null; + } + + /** + * @internal + * + * @param callable $httpHandler + * @param string $regionUrl + * @param array $headers Request headers to send in with the request. + */ + public static function getRegionFromUrl(callable $httpHandler, string $regionUrl, array $headers): string + { + // get the region/zone from the region URL + $regionRequest = new Request('GET', $regionUrl, $headers); + $regionResponse = $httpHandler($regionRequest); + + // Remove last character. For example, if us-east-2b is returned, + // the region would be us-east-2. + return substr((string) $regionResponse->getBody(), 0, -1); + } + + /** + * @internal + * + * @param callable $httpHandler + * @param string $securityCredentialsUrl + * @param array $headers Request headers to send in with the request. + */ + public static function getRoleName(callable $httpHandler, string $securityCredentialsUrl, array $headers): string + { + // Get the AWS role name + $roleRequest = new Request('GET', $securityCredentialsUrl, $headers); + $roleResponse = $httpHandler($roleRequest); + $roleName = (string) $roleResponse->getBody(); + + return $roleName; + } + + /** + * @internal + * + * @param callable $httpHandler + * @param string $securityCredentialsUrl + * @param array $headers Request headers to send in with the request. + * @return array{string, string, ?string} + */ + public static function getSigningVarsFromUrl( + callable $httpHandler, + string $securityCredentialsUrl, + string $roleName, + array $headers + ): array { + // Get the AWS credentials + $credsRequest = new Request( + 'GET', + $securityCredentialsUrl . '/' . $roleName, + $headers + ); + $credsResponse = $httpHandler($credsRequest); + $awsCreds = json_decode((string) $credsResponse->getBody(), true); + return [ + $awsCreds['AccessKeyId'], // accessKeyId + $awsCreds['SecretAccessKey'], // secretAccessKey + $awsCreds['Token'], // token + ]; + } + + /** + * @internal + * + * @return array{string, string, ?string} + */ + public static function getSigningVarsFromEnv(): ?array + { + $accessKeyId = getenv('AWS_ACCESS_KEY_ID'); + $secretAccessKey = getenv('AWS_SECRET_ACCESS_KEY'); + if ($accessKeyId && $secretAccessKey) { + return [ + $accessKeyId, + $secretAccessKey, + getenv('AWS_SESSION_TOKEN') ?: null, // session token (can be null) + ]; + } + + return null; + } + + /** + * Return HMAC hash in binary string + */ + private static function hmacSign(string $key, string $msg): string + { + return hash_hmac('sha256', self::utf8Encode($msg), $key, true); + } + + /** + * @TODO add a fallback when mbstring is not available + */ + private static function utf8Encode(string $string): string + { + return mb_convert_encoding($string, 'UTF-8', 'ISO-8859-1'); + } + + private static function getSignatureKey( + string $key, + string $dateStamp, + string $regionName, + string $serviceName + ): string { + $kDate = self::hmacSign(self::utf8Encode('AWS4' . $key), $dateStamp); + $kRegion = self::hmacSign($kDate, $regionName); + $kService = self::hmacSign($kRegion, $serviceName); + $kSigning = self::hmacSign($kService, 'aws4_request'); + + return $kSigning; + } +} diff --git a/vendor/google/auth/src/CredentialSource/FileSource.php b/vendor/google/auth/src/CredentialSource/FileSource.php new file mode 100644 index 0000000..e2afc6c --- /dev/null +++ b/vendor/google/auth/src/CredentialSource/FileSource.php @@ -0,0 +1,75 @@ +file = $file; + + if ($format === 'json' && is_null($subjectTokenFieldName)) { + throw new InvalidArgumentException( + 'subject_token_field_name must be set when format is JSON' + ); + } + + $this->format = $format; + $this->subjectTokenFieldName = $subjectTokenFieldName; + } + + public function fetchSubjectToken(callable $httpHandler = null): string + { + $contents = file_get_contents($this->file); + if ($this->format === 'json') { + if (!$json = json_decode((string) $contents, true)) { + throw new UnexpectedValueException( + 'Unable to decode JSON file' + ); + } + if (!isset($json[$this->subjectTokenFieldName])) { + throw new UnexpectedValueException( + 'subject_token_field_name not found in JSON file' + ); + } + $contents = $json[$this->subjectTokenFieldName]; + } + + return $contents; + } +} diff --git a/vendor/google/auth/src/CredentialSource/UrlSource.php b/vendor/google/auth/src/CredentialSource/UrlSource.php new file mode 100644 index 0000000..0acb3c6 --- /dev/null +++ b/vendor/google/auth/src/CredentialSource/UrlSource.php @@ -0,0 +1,97 @@ + + */ + private ?array $headers; + + /** + * @param string $url The URL to fetch the subject token from. + * @param string $format The format of the token in the response. Can be null or "json". + * @param string $subjectTokenFieldName The name of the field containing the token in the response. This is required + * when format is "json". + * @param array $headers Request headers to send in with the request to the URL. + */ + public function __construct( + string $url, + string $format = null, + string $subjectTokenFieldName = null, + array $headers = null + ) { + $this->url = $url; + + if ($format === 'json' && is_null($subjectTokenFieldName)) { + throw new InvalidArgumentException( + 'subject_token_field_name must be set when format is JSON' + ); + } + + $this->format = $format; + $this->subjectTokenFieldName = $subjectTokenFieldName; + $this->headers = $headers; + } + + public function fetchSubjectToken(callable $httpHandler = null): string + { + if (is_null($httpHandler)) { + $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + + $request = new Request( + 'GET', + $this->url, + $this->headers ?: [] + ); + + $response = $httpHandler($request); + $body = (string) $response->getBody(); + if ($this->format === 'json') { + if (!$json = json_decode((string) $body, true)) { + throw new UnexpectedValueException( + 'Unable to decode JSON response' + ); + } + if (!isset($json[$this->subjectTokenFieldName])) { + throw new UnexpectedValueException( + 'subject_token_field_name not found in JSON file' + ); + } + $body = $json[$this->subjectTokenFieldName]; + } + + return $body; + } +} diff --git a/vendor/google/auth/src/Credentials/AppIdentityCredentials.php b/vendor/google/auth/src/Credentials/AppIdentityCredentials.php new file mode 100644 index 0000000..db29438 --- /dev/null +++ b/vendor/google/auth/src/Credentials/AppIdentityCredentials.php @@ -0,0 +1,238 @@ +push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/books/v1', + * 'auth' => 'google_auth' + * ]); + * + * $res = $client->get('volumes?q=Henry+David+Thoreau&country=US'); + * ``` + */ +class AppIdentityCredentials extends CredentialsLoader implements + SignBlobInterface, + ProjectIdProviderInterface +{ + /** + * Result of fetchAuthToken. + * + * @var array + */ + protected $lastReceivedToken; + + /** + * Array of OAuth2 scopes to be requested. + * + * @var string[] + */ + private $scope; + + /** + * @var string + */ + private $clientName; + + /** + * @param string|string[] $scope One or more scopes. + */ + public function __construct($scope = []) + { + $this->scope = is_array($scope) ? $scope : explode(' ', (string) $scope); + } + + /** + * Determines if this an App Engine instance, by accessing the + * SERVER_SOFTWARE environment variable (prod) or the APPENGINE_RUNTIME + * environment variable (dev). + * + * @return bool true if this an App Engine Instance, false otherwise + */ + public static function onAppEngine() + { + $appEngineProduction = isset($_SERVER['SERVER_SOFTWARE']) && + 0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine'); + if ($appEngineProduction) { + return true; + } + $appEngineDevAppServer = isset($_SERVER['APPENGINE_RUNTIME']) && + $_SERVER['APPENGINE_RUNTIME'] == 'php'; + if ($appEngineDevAppServer) { + return true; + } + return false; + } + + /** + * Implements FetchAuthTokenInterface#fetchAuthToken. + * + * Fetches the auth tokens using the AppIdentityService if available. + * As the AppIdentityService uses protobufs to fetch the access token, + * the GuzzleHttp\ClientInterface instance passed in will not be used. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type string $expiration_time + * } + */ + public function fetchAuthToken(callable $httpHandler = null) + { + try { + $this->checkAppEngineContext(); + } catch (\Exception $e) { + return []; + } + + /** @phpstan-ignore-next-line */ + $token = AppIdentityService::getAccessToken($this->scope); + $this->lastReceivedToken = $token; + + return $token; + } + + /** + * Sign a string using AppIdentityService. + * + * @param string $stringToSign The string to sign. + * @param bool $forceOpenSsl [optional] Does not apply to this credentials + * type. + * @return string The signature, base64-encoded. + * @throws \Exception If AppEngine SDK or mock is not available. + */ + public function signBlob($stringToSign, $forceOpenSsl = false) + { + $this->checkAppEngineContext(); + + /** @phpstan-ignore-next-line */ + return base64_encode(AppIdentityService::signForApp($stringToSign)['signature']); + } + + /** + * Get the project ID from AppIdentityService. + * + * Returns null if AppIdentityService is unavailable. + * + * @param callable $httpHandler Not used by this type. + * @return string|null + */ + public function getProjectId(callable $httpHandler = null) + { + try { + $this->checkAppEngineContext(); + } catch (\Exception $e) { + return null; + } + + /** @phpstan-ignore-next-line */ + return AppIdentityService::getApplicationId(); + } + + /** + * Get the client name from AppIdentityService. + * + * Subsequent calls to this method will return a cached value. + * + * @param callable $httpHandler Not used in this implementation. + * @return string + * @throws \Exception If AppEngine SDK or mock is not available. + */ + public function getClientName(callable $httpHandler = null) + { + $this->checkAppEngineContext(); + + if (!$this->clientName) { + /** @phpstan-ignore-next-line */ + $this->clientName = AppIdentityService::getServiceAccountName(); + } + + return $this->clientName; + } + + /** + * @return array{access_token:string,expires_at:int}|null + */ + public function getLastReceivedToken() + { + if ($this->lastReceivedToken) { + return [ + 'access_token' => $this->lastReceivedToken['access_token'], + 'expires_at' => $this->lastReceivedToken['expiration_time'], + ]; + } + + return null; + } + + /** + * Caching is handled by the underlying AppIdentityService, return empty string + * to prevent caching. + * + * @return string + */ + public function getCacheKey() + { + return ''; + } + + /** + * @return void + */ + private function checkAppEngineContext() + { + if (!self::onAppEngine() || !class_exists('google\appengine\api\app_identity\AppIdentityService')) { + throw new \Exception( + 'This class must be run in App Engine, or you must include the AppIdentityService ' + . 'mock class defined in tests/mocks/AppIdentityService.php' + ); + } + } +} diff --git a/vendor/google/auth/src/Credentials/ExternalAccountCredentials.php b/vendor/google/auth/src/Credentials/ExternalAccountCredentials.php new file mode 100644 index 0000000..bc4a686 --- /dev/null +++ b/vendor/google/auth/src/Credentials/ExternalAccountCredentials.php @@ -0,0 +1,328 @@ + $jsonKey JSON credentials as an associative array. + */ + public function __construct( + $scope, + array $jsonKey + ) { + if (!array_key_exists('type', $jsonKey)) { + throw new InvalidArgumentException('json key is missing the type field'); + } + if ($jsonKey['type'] !== self::EXTERNAL_ACCOUNT_TYPE) { + throw new InvalidArgumentException(sprintf( + 'expected "%s" type but received "%s"', + self::EXTERNAL_ACCOUNT_TYPE, + $jsonKey['type'] + )); + } + + if (!array_key_exists('token_url', $jsonKey)) { + throw new InvalidArgumentException( + 'json key is missing the token_url field' + ); + } + + if (!array_key_exists('audience', $jsonKey)) { + throw new InvalidArgumentException( + 'json key is missing the audience field' + ); + } + + if (!array_key_exists('subject_token_type', $jsonKey)) { + throw new InvalidArgumentException( + 'json key is missing the subject_token_type field' + ); + } + + if (!array_key_exists('credential_source', $jsonKey)) { + throw new InvalidArgumentException( + 'json key is missing the credential_source field' + ); + } + + if (array_key_exists('service_account_impersonation_url', $jsonKey)) { + $this->serviceAccountImpersonationUrl = $jsonKey['service_account_impersonation_url']; + } + + $this->quotaProject = $jsonKey['quota_project_id'] ?? null; + $this->workforcePoolUserProject = $jsonKey['workforce_pool_user_project'] ?? null; + $this->universeDomain = $jsonKey['universe_domain'] ?? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + + $this->auth = new OAuth2([ + 'tokenCredentialUri' => $jsonKey['token_url'], + 'audience' => $jsonKey['audience'], + 'scope' => $scope, + 'subjectTokenType' => $jsonKey['subject_token_type'], + 'subjectTokenFetcher' => self::buildCredentialSource($jsonKey), + 'additionalOptions' => $this->workforcePoolUserProject + ? ['userProject' => $this->workforcePoolUserProject] + : [], + ]); + + if (!$this->isWorkforcePool() && $this->workforcePoolUserProject) { + throw new InvalidArgumentException( + 'workforce_pool_user_project should not be set for non-workforce pool credentials.' + ); + } + } + + /** + * @param array $jsonKey + */ + private static function buildCredentialSource(array $jsonKey): ExternalAccountCredentialSourceInterface + { + $credentialSource = $jsonKey['credential_source']; + if (isset($credentialSource['file'])) { + return new FileSource( + $credentialSource['file'], + $credentialSource['format']['type'] ?? null, + $credentialSource['format']['subject_token_field_name'] ?? null + ); + } + + if ( + isset($credentialSource['environment_id']) + && 1 === preg_match('/^aws(\d+)$/', $credentialSource['environment_id'], $matches) + ) { + if ($matches[1] !== '1') { + throw new InvalidArgumentException( + "aws version \"$matches[1]\" is not supported in the current build." + ); + } + if (!array_key_exists('regional_cred_verification_url', $credentialSource)) { + throw new InvalidArgumentException( + 'The regional_cred_verification_url field is required for aws1 credential source.' + ); + } + if (!array_key_exists('audience', $jsonKey)) { + throw new InvalidArgumentException( + 'aws1 credential source requires an audience to be set in the JSON file.' + ); + } + + return new AwsNativeSource( + $jsonKey['audience'], + $credentialSource['regional_cred_verification_url'], // $regionalCredVerificationUrl + $credentialSource['region_url'] ?? null, // $regionUrl + $credentialSource['url'] ?? null, // $securityCredentialsUrl + $credentialSource['imdsv2_session_token_url'] ?? null, // $imdsV2TokenUrl + ); + } + + if (isset($credentialSource['url'])) { + return new UrlSource( + $credentialSource['url'], + $credentialSource['format']['type'] ?? null, + $credentialSource['format']['subject_token_field_name'] ?? null, + $credentialSource['headers'] ?? null, + ); + } + + throw new InvalidArgumentException('Unable to determine credential source from json key.'); + } + + /** + * @param string $stsToken + * @param callable $httpHandler + * + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_at + * } + */ + private function getImpersonatedAccessToken(string $stsToken, callable $httpHandler = null): array + { + if (!isset($this->serviceAccountImpersonationUrl)) { + throw new InvalidArgumentException( + 'service_account_impersonation_url must be set in JSON credentials.' + ); + } + $request = new Request( + 'POST', + $this->serviceAccountImpersonationUrl, + [ + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $stsToken, + ], + (string) json_encode([ + 'lifetime' => sprintf('%ss', OAuth2::DEFAULT_EXPIRY_SECONDS), + 'scope' => explode(' ', $this->auth->getScope()), + ]), + ); + if (is_null($httpHandler)) { + $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + $response = $httpHandler($request); + $body = json_decode((string) $response->getBody(), true); + return [ + 'access_token' => $body['accessToken'], + 'expires_at' => strtotime($body['expireTime']), + ]; + } + + /** + * @param callable $httpHandler + * + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_at (impersonated service accounts only) + * @type int $expires_in (identity pool only) + * @type string $issued_token_type (identity pool only) + * @type string $token_type (identity pool only) + * } + */ + public function fetchAuthToken(callable $httpHandler = null) + { + $stsToken = $this->auth->fetchAuthToken($httpHandler); + + if (isset($this->serviceAccountImpersonationUrl)) { + return $this->getImpersonatedAccessToken($stsToken['access_token'], $httpHandler); + } + + return $stsToken; + } + + public function getCacheKey() + { + return $this->auth->getCacheKey(); + } + + public function getLastReceivedToken() + { + return $this->auth->getLastReceivedToken(); + } + + /** + * Get the quota project used for this API request + * + * @return string|null + */ + public function getQuotaProject() + { + return $this->quotaProject; + } + + /** + * Get the universe domain used for this API request + * + * @return string + */ + public function getUniverseDomain(): string + { + return $this->universeDomain; + } + + /** + * Get the project ID. + * + * @param callable $httpHandler Callback which delivers psr7 request + * @param string $accessToken The access token to use to sign the blob. If + * provided, saves a call to the metadata server for a new access + * token. **Defaults to** `null`. + * @return string|null + */ + public function getProjectId(callable $httpHandler = null, string $accessToken = null) + { + if (isset($this->projectId)) { + return $this->projectId; + } + + $projectNumber = $this->getProjectNumber() ?: $this->workforcePoolUserProject; + if (!$projectNumber) { + return null; + } + + if (is_null($httpHandler)) { + $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + + $url = str_replace( + 'UNIVERSE_DOMAIN', + $this->getUniverseDomain(), + sprintf(self::CLOUD_RESOURCE_MANAGER_URL, $projectNumber) + ); + + if (is_null($accessToken)) { + $accessToken = $this->fetchAuthToken($httpHandler)['access_token']; + } + + $request = new Request('GET', $url, ['authorization' => 'Bearer ' . $accessToken]); + $response = $httpHandler($request); + + $body = json_decode((string) $response->getBody(), true); + return $this->projectId = $body['projectId']; + } + + private function getProjectNumber(): ?string + { + $parts = explode('/', $this->auth->getAudience()); + $i = array_search('projects', $parts); + return $parts[$i + 1] ?? null; + } + + private function isWorkforcePool(): bool + { + $regex = '#//iam\.googleapis\.com/locations/[^/]+/workforcePools/#'; + return preg_match($regex, $this->auth->getAudience()) === 1; + } +} diff --git a/vendor/google/auth/src/Credentials/GCECredentials.php b/vendor/google/auth/src/Credentials/GCECredentials.php new file mode 100644 index 0000000..2b704aa --- /dev/null +++ b/vendor/google/auth/src/Credentials/GCECredentials.php @@ -0,0 +1,622 @@ +push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'auth' => 'google_auth' + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + */ +class GCECredentials extends CredentialsLoader implements + SignBlobInterface, + ProjectIdProviderInterface, + GetQuotaProjectInterface +{ + use IamSignerTrait; + + // phpcs:disable + const cacheKey = 'GOOGLE_AUTH_PHP_GCE'; + // phpcs:enable + + /** + * The metadata IP address on appengine instances. + * + * The IP is used instead of the domain 'metadata' to avoid slow responses + * when not on Compute Engine. + */ + const METADATA_IP = '169.254.169.254'; + + /** + * The metadata path of the default token. + */ + const TOKEN_URI_PATH = 'v1/instance/service-accounts/default/token'; + + /** + * The metadata path of the default id token. + */ + const ID_TOKEN_URI_PATH = 'v1/instance/service-accounts/default/identity'; + + /** + * The metadata path of the client ID. + */ + const CLIENT_ID_URI_PATH = 'v1/instance/service-accounts/default/email'; + + /** + * The metadata path of the project ID. + */ + const PROJECT_ID_URI_PATH = 'v1/project/project-id'; + + /** + * The metadata path of the project ID. + */ + const UNIVERSE_DOMAIN_URI_PATH = 'v1/universe/universe_domain'; + + /** + * The header whose presence indicates GCE presence. + */ + const FLAVOR_HEADER = 'Metadata-Flavor'; + + /** + * The Linux file which contains the product name. + */ + private const GKE_PRODUCT_NAME_FILE = '/sys/class/dmi/id/product_name'; + + /** + * Note: the explicit `timeout` and `tries` below is a workaround. The underlying + * issue is that resolving an unknown host on some networks will take + * 20-30 seconds; making this timeout short fixes the issue, but + * could lead to false negatives in the event that we are on GCE, but + * the metadata resolution was particularly slow. The latter case is + * "unlikely" since the expected 4-nines time is about 0.5 seconds. + * This allows us to limit the total ping maximum timeout to 1.5 seconds + * for developer desktop scenarios. + */ + const MAX_COMPUTE_PING_TRIES = 3; + const COMPUTE_PING_CONNECTION_TIMEOUT_S = 0.5; + + /** + * Flag used to ensure that the onGCE test is only done once;. + * + * @var bool + */ + private $hasCheckedOnGce = false; + + /** + * Flag that stores the value of the onGCE check. + * + * @var bool + */ + private $isOnGce = false; + + /** + * Result of fetchAuthToken. + * + * @var array + */ + protected $lastReceivedToken; + + /** + * @var string|null + */ + private $clientName; + + /** + * @var string|null + */ + private $projectId; + + /** + * @var string + */ + private $tokenUri; + + /** + * @var string + */ + private $targetAudience; + + /** + * @var string|null + */ + private $quotaProject; + + /** + * @var string|null + */ + private $serviceAccountIdentity; + + /** + * @var string + */ + private ?string $universeDomain; + + /** + * @param Iam $iam [optional] An IAM instance. + * @param string|string[] $scope [optional] the scope of the access request, + * expressed either as an array or as a space-delimited string. + * @param string $targetAudience [optional] The audience for the ID token. + * @param string $quotaProject [optional] Specifies a project to bill for access + * charges associated with the request. + * @param string $serviceAccountIdentity [optional] Specify a service + * account identity name to use instead of "default". + * @param string $universeDomain [optional] Specify a universe domain to use + * instead of fetching one from the metadata server. + */ + public function __construct( + Iam $iam = null, + $scope = null, + $targetAudience = null, + $quotaProject = null, + $serviceAccountIdentity = null, + string $universeDomain = null + ) { + $this->iam = $iam; + + if ($scope && $targetAudience) { + throw new InvalidArgumentException( + 'Scope and targetAudience cannot both be supplied' + ); + } + + $tokenUri = self::getTokenUri($serviceAccountIdentity); + if ($scope) { + if (is_string($scope)) { + $scope = explode(' ', $scope); + } + + $scope = implode(',', $scope); + + $tokenUri = $tokenUri . '?scopes=' . $scope; + } elseif ($targetAudience) { + $tokenUri = self::getIdTokenUri($serviceAccountIdentity); + $tokenUri = $tokenUri . '?audience=' . $targetAudience; + $this->targetAudience = $targetAudience; + } + + $this->tokenUri = $tokenUri; + $this->quotaProject = $quotaProject; + $this->serviceAccountIdentity = $serviceAccountIdentity; + $this->universeDomain = $universeDomain; + } + + /** + * The full uri for accessing the default token. + * + * @param string $serviceAccountIdentity [optional] Specify a service + * account identity name to use instead of "default". + * @return string + */ + public static function getTokenUri($serviceAccountIdentity = null) + { + $base = 'http://' . self::METADATA_IP . '/computeMetadata/'; + $base .= self::TOKEN_URI_PATH; + + if ($serviceAccountIdentity) { + return str_replace( + '/default/', + '/' . $serviceAccountIdentity . '/', + $base + ); + } + return $base; + } + + /** + * The full uri for accessing the default service account. + * + * @param string $serviceAccountIdentity [optional] Specify a service + * account identity name to use instead of "default". + * @return string + */ + public static function getClientNameUri($serviceAccountIdentity = null) + { + $base = 'http://' . self::METADATA_IP . '/computeMetadata/'; + $base .= self::CLIENT_ID_URI_PATH; + + if ($serviceAccountIdentity) { + return str_replace( + '/default/', + '/' . $serviceAccountIdentity . '/', + $base + ); + } + + return $base; + } + + /** + * The full uri for accesesing the default identity token. + * + * @param string $serviceAccountIdentity [optional] Specify a service + * account identity name to use instead of "default". + * @return string + */ + private static function getIdTokenUri($serviceAccountIdentity = null) + { + $base = 'http://' . self::METADATA_IP . '/computeMetadata/'; + $base .= self::ID_TOKEN_URI_PATH; + + if ($serviceAccountIdentity) { + return str_replace( + '/default/', + '/' . $serviceAccountIdentity . '/', + $base + ); + } + + return $base; + } + + /** + * The full uri for accessing the default project ID. + * + * @return string + */ + private static function getProjectIdUri() + { + $base = 'http://' . self::METADATA_IP . '/computeMetadata/'; + + return $base . self::PROJECT_ID_URI_PATH; + } + + /** + * The full uri for accessing the default universe domain. + * + * @return string + */ + private static function getUniverseDomainUri() + { + $base = 'http://' . self::METADATA_IP . '/computeMetadata/'; + + return $base . self::UNIVERSE_DOMAIN_URI_PATH; + } + + /** + * Determines if this an App Engine Flexible instance, by accessing the + * GAE_INSTANCE environment variable. + * + * @return bool true if this an App Engine Flexible Instance, false otherwise + */ + public static function onAppEngineFlexible() + { + return substr((string) getenv('GAE_INSTANCE'), 0, 4) === 'aef-'; + } + + /** + * Determines if this a GCE instance, by accessing the expected metadata + * host. + * If $httpHandler is not specified a the default HttpHandler is used. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return bool True if this a GCEInstance, false otherwise + */ + public static function onGce(callable $httpHandler = null) + { + $httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + + $checkUri = 'http://' . self::METADATA_IP; + for ($i = 1; $i <= self::MAX_COMPUTE_PING_TRIES; $i++) { + try { + // Comment from: oauth2client/client.py + // + // Note: the explicit `timeout` below is a workaround. The underlying + // issue is that resolving an unknown host on some networks will take + // 20-30 seconds; making this timeout short fixes the issue, but + // could lead to false negatives in the event that we are on GCE, but + // the metadata resolution was particularly slow. The latter case is + // "unlikely". + $resp = $httpHandler( + new Request( + 'GET', + $checkUri, + [self::FLAVOR_HEADER => 'Google'] + ), + ['timeout' => self::COMPUTE_PING_CONNECTION_TIMEOUT_S] + ); + + return $resp->getHeaderLine(self::FLAVOR_HEADER) == 'Google'; + } catch (ClientException $e) { + } catch (ServerException $e) { + } catch (RequestException $e) { + } catch (ConnectException $e) { + } + } + + if (PHP_OS === 'Windows') { + // @TODO: implement GCE residency detection on Windows + return false; + } + + // Detect GCE residency on Linux + return self::detectResidencyLinux(self::GKE_PRODUCT_NAME_FILE); + } + + private static function detectResidencyLinux(string $productNameFile): bool + { + if (file_exists($productNameFile)) { + $productName = trim((string) file_get_contents($productNameFile)); + return 0 === strpos($productName, 'Google'); + } + return false; + } + + /** + * Implements FetchAuthTokenInterface#fetchAuthToken. + * + * Fetches the auth tokens from the GCE metadata host if it is available. + * If $httpHandler is not specified a the default HttpHandler is used. + * + * @param callable $httpHandler callback which delivers psr7 request + * + * @return array { + * A set of auth related metadata, based on the token type. + * + * @type string $access_token for access tokens + * @type int $expires_in for access tokens + * @type string $token_type for access tokens + * @type string $id_token for ID tokens + * } + * @throws \Exception + */ + public function fetchAuthToken(callable $httpHandler = null) + { + $httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + + if (!$this->hasCheckedOnGce) { + $this->isOnGce = self::onGce($httpHandler); + $this->hasCheckedOnGce = true; + } + if (!$this->isOnGce) { + return []; // return an empty array with no access token + } + + $response = $this->getFromMetadata($httpHandler, $this->tokenUri); + + if ($this->targetAudience) { + return $this->lastReceivedToken = ['id_token' => $response]; + } + + if (null === $json = json_decode($response, true)) { + throw new \Exception('Invalid JSON response'); + } + + $json['expires_at'] = time() + $json['expires_in']; + + // store this so we can retrieve it later + $this->lastReceivedToken = $json; + + return $json; + } + + /** + * @return string + */ + public function getCacheKey() + { + return self::cacheKey; + } + + /** + * @return array|null + */ + public function getLastReceivedToken() + { + if ($this->lastReceivedToken) { + if (array_key_exists('id_token', $this->lastReceivedToken)) { + return $this->lastReceivedToken; + } + + return [ + 'access_token' => $this->lastReceivedToken['access_token'], + 'expires_at' => $this->lastReceivedToken['expires_at'] + ]; + } + + return null; + } + + /** + * Get the client name from GCE metadata. + * + * Subsequent calls will return a cached value. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return string + */ + public function getClientName(callable $httpHandler = null) + { + if ($this->clientName) { + return $this->clientName; + } + + $httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + + if (!$this->hasCheckedOnGce) { + $this->isOnGce = self::onGce($httpHandler); + $this->hasCheckedOnGce = true; + } + + if (!$this->isOnGce) { + return ''; + } + + $this->clientName = $this->getFromMetadata( + $httpHandler, + self::getClientNameUri($this->serviceAccountIdentity) + ); + + return $this->clientName; + } + + /** + * Fetch the default Project ID from compute engine. + * + * Returns null if called outside GCE. + * + * @param callable $httpHandler Callback which delivers psr7 request + * @return string|null + */ + public function getProjectId(callable $httpHandler = null) + { + if ($this->projectId) { + return $this->projectId; + } + + $httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + + if (!$this->hasCheckedOnGce) { + $this->isOnGce = self::onGce($httpHandler); + $this->hasCheckedOnGce = true; + } + + if (!$this->isOnGce) { + return null; + } + + $this->projectId = $this->getFromMetadata($httpHandler, self::getProjectIdUri()); + return $this->projectId; + } + + /** + * Fetch the default universe domain from the metadata server. + * + * @param callable $httpHandler Callback which delivers psr7 request + * @return string + */ + public function getUniverseDomain(callable $httpHandler = null): string + { + if (null !== $this->universeDomain) { + return $this->universeDomain; + } + + $httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + + if (!$this->hasCheckedOnGce) { + $this->isOnGce = self::onGce($httpHandler); + $this->hasCheckedOnGce = true; + } + + try { + $this->universeDomain = $this->getFromMetadata( + $httpHandler, + self::getUniverseDomainUri() + ); + } catch (ClientException $e) { + // If the metadata server exists, but returns a 404 for the universe domain, the auth + // libraries should safely assume this is an older metadata server running in GCU, and + // should return the default universe domain. + if (!$e->hasResponse() || 404 != $e->getResponse()->getStatusCode()) { + throw $e; + } + $this->universeDomain = self::DEFAULT_UNIVERSE_DOMAIN; + } + + // We expect in some cases the metadata server will return an empty string for the universe + // domain. In this case, the auth library MUST return the default universe domain. + if ('' === $this->universeDomain) { + $this->universeDomain = self::DEFAULT_UNIVERSE_DOMAIN; + } + + return $this->universeDomain; + } + + /** + * Fetch the value of a GCE metadata server URI. + * + * @param callable $httpHandler An HTTP Handler to deliver PSR7 requests. + * @param string $uri The metadata URI. + * @return string + */ + private function getFromMetadata(callable $httpHandler, $uri) + { + $resp = $httpHandler( + new Request( + 'GET', + $uri, + [self::FLAVOR_HEADER => 'Google'] + ) + ); + + return (string) $resp->getBody(); + } + + /** + * Get the quota project used for this API request + * + * @return string|null + */ + public function getQuotaProject() + { + return $this->quotaProject; + } + + /** + * Set whether or not we've already checked the GCE environment. + * + * @param bool $isOnGce + * + * @return void + */ + public function setIsOnGce($isOnGce) + { + // Implicitly set hasCheckedGce to true + $this->hasCheckedOnGce = true; + + // Set isOnGce + $this->isOnGce = $isOnGce; + } +} diff --git a/vendor/google/auth/src/Credentials/IAMCredentials.php b/vendor/google/auth/src/Credentials/IAMCredentials.php new file mode 100644 index 0000000..98780c6 --- /dev/null +++ b/vendor/google/auth/src/Credentials/IAMCredentials.php @@ -0,0 +1,91 @@ +selector = $selector; + $this->token = $token; + } + + /** + * export a callback function which updates runtime metadata. + * + * @return callable updateMetadata function + */ + public function getUpdateMetadataFunc() + { + return [$this, 'updateMetadata']; + } + + /** + * Updates metadata with the appropriate header metadata. + * + * @param array $metadata metadata hashmap + * @param string $unusedAuthUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * Note: this param is unused here, only included here for + * consistency with other credentials class + * + * @return array updated metadata hashmap + */ + public function updateMetadata( + $metadata, + $unusedAuthUri = null, + callable $httpHandler = null + ) { + $metadata_copy = $metadata; + $metadata_copy[self::SELECTOR_KEY] = $this->selector; + $metadata_copy[self::TOKEN_KEY] = $this->token; + + return $metadata_copy; + } +} diff --git a/vendor/google/auth/src/Credentials/ImpersonatedServiceAccountCredentials.php b/vendor/google/auth/src/Credentials/ImpersonatedServiceAccountCredentials.php new file mode 100644 index 0000000..1b4e46e --- /dev/null +++ b/vendor/google/auth/src/Credentials/ImpersonatedServiceAccountCredentials.php @@ -0,0 +1,142 @@ + $jsonKey JSON credential file path or JSON credentials + * as an associative array. + */ + public function __construct( + $scope, + $jsonKey + ) { + if (is_string($jsonKey)) { + if (!file_exists($jsonKey)) { + throw new \InvalidArgumentException('file does not exist'); + } + $json = file_get_contents($jsonKey); + if (!$jsonKey = json_decode((string) $json, true)) { + throw new \LogicException('invalid json for auth config'); + } + } + if (!array_key_exists('service_account_impersonation_url', $jsonKey)) { + throw new \LogicException( + 'json key is missing the service_account_impersonation_url field' + ); + } + if (!array_key_exists('source_credentials', $jsonKey)) { + throw new \LogicException('json key is missing the source_credentials field'); + } + + $this->impersonatedServiceAccountName = $this->getImpersonatedServiceAccountNameFromUrl( + $jsonKey['service_account_impersonation_url'] + ); + + $this->sourceCredentials = new UserRefreshCredentials( + $scope, + $jsonKey['source_credentials'] + ); + } + + /** + * Helper function for extracting the Server Account Name from the URL saved in the account + * credentials file. + * + * @param $serviceAccountImpersonationUrl string URL from "service_account_impersonation_url" + * @return string Service account email or ID. + */ + private function getImpersonatedServiceAccountNameFromUrl( + string $serviceAccountImpersonationUrl + ): string { + $fields = explode('/', $serviceAccountImpersonationUrl); + $lastField = end($fields); + $splitter = explode(':', $lastField); + return $splitter[0]; + } + + /** + * Get the client name from the keyfile + * + * In this implementation, it will return the issuers email from the oauth token. + * + * @param callable|null $unusedHttpHandler not used by this credentials type. + * @return string Token issuer email + */ + public function getClientName(callable $unusedHttpHandler = null) + { + return $this->impersonatedServiceAccountName; + } + + /** + * @param callable $httpHandler + * + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_in + * @type string $scope + * @type string $token_type + * @type string $id_token + * } + */ + public function fetchAuthToken(callable $httpHandler = null) + { + return $this->sourceCredentials->fetchAuthToken($httpHandler); + } + + /** + * @return string + */ + public function getCacheKey() + { + return $this->sourceCredentials->getCacheKey(); + } + + /** + * @return array + */ + public function getLastReceivedToken() + { + return $this->sourceCredentials->getLastReceivedToken(); + } +} diff --git a/vendor/google/auth/src/Credentials/InsecureCredentials.php b/vendor/google/auth/src/Credentials/InsecureCredentials.php new file mode 100644 index 0000000..9b9e24b --- /dev/null +++ b/vendor/google/auth/src/Credentials/InsecureCredentials.php @@ -0,0 +1,68 @@ + '' + ]; + + /** + * Fetches the auth token. In this case it returns an empty string. + * + * @param callable $httpHandler + * @return array{access_token:string} A set of auth related metadata + */ + public function fetchAuthToken(callable $httpHandler = null) + { + return $this->token; + } + + /** + * Returns the cache key. In this case it returns a null value, disabling + * caching. + * + * @return string|null + */ + public function getCacheKey() + { + return null; + } + + /** + * Fetches the last received token. In this case, it returns the same empty string + * auth token. + * + * @return array{access_token:string} + */ + public function getLastReceivedToken() + { + return $this->token; + } +} diff --git a/vendor/google/auth/src/Credentials/ServiceAccountCredentials.php b/vendor/google/auth/src/Credentials/ServiceAccountCredentials.php new file mode 100644 index 0000000..eba43cf --- /dev/null +++ b/vendor/google/auth/src/Credentials/ServiceAccountCredentials.php @@ -0,0 +1,383 @@ +push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'auth' => 'google_auth' // authorize all requests + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + */ +class ServiceAccountCredentials extends CredentialsLoader implements + GetQuotaProjectInterface, + SignBlobInterface, + ProjectIdProviderInterface +{ + use ServiceAccountSignerTrait; + + /** + * The OAuth2 instance used to conduct authorization. + * + * @var OAuth2 + */ + protected $auth; + + /** + * The quota project associated with the JSON credentials + * + * @var string + */ + protected $quotaProject; + + /** + * @var string|null + */ + protected $projectId; + + /** + * @var array|null + */ + private $lastReceivedJwtAccessToken; + + /** + * @var bool + */ + private $useJwtAccessWithScope = false; + + /** + * @var ServiceAccountJwtAccessCredentials|null + */ + private $jwtAccessCredentials; + + /** + * @var string + */ + private string $universeDomain; + + /** + * Create a new ServiceAccountCredentials. + * + * @param string|string[]|null $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + * @param string|array $jsonKey JSON credential file path or JSON credentials + * as an associative array + * @param string $sub an email address account to impersonate, in situations when + * the service account has been delegated domain wide access. + * @param string $targetAudience The audience for the ID token. + */ + public function __construct( + $scope, + $jsonKey, + $sub = null, + $targetAudience = null + ) { + if (is_string($jsonKey)) { + if (!file_exists($jsonKey)) { + throw new \InvalidArgumentException('file does not exist'); + } + $jsonKeyStream = file_get_contents($jsonKey); + if (!$jsonKey = json_decode((string) $jsonKeyStream, true)) { + throw new \LogicException('invalid json for auth config'); + } + } + if (!array_key_exists('client_email', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the client_email field' + ); + } + if (!array_key_exists('private_key', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the private_key field' + ); + } + if (array_key_exists('quota_project_id', $jsonKey)) { + $this->quotaProject = (string) $jsonKey['quota_project_id']; + } + if ($scope && $targetAudience) { + throw new InvalidArgumentException( + 'Scope and targetAudience cannot both be supplied' + ); + } + $additionalClaims = []; + if ($targetAudience) { + $additionalClaims = ['target_audience' => $targetAudience]; + } + $this->auth = new OAuth2([ + 'audience' => self::TOKEN_CREDENTIAL_URI, + 'issuer' => $jsonKey['client_email'], + 'scope' => $scope, + 'signingAlgorithm' => 'RS256', + 'signingKey' => $jsonKey['private_key'], + 'sub' => $sub, + 'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI, + 'additionalClaims' => $additionalClaims, + ]); + + $this->projectId = $jsonKey['project_id'] ?? null; + $this->universeDomain = $jsonKey['universe_domain'] ?? self::DEFAULT_UNIVERSE_DOMAIN; + } + + /** + * When called, the ServiceAccountCredentials will use an instance of + * ServiceAccountJwtAccessCredentials to fetch (self-sign) an access token + * even when only scopes are supplied. Otherwise, + * ServiceAccountJwtAccessCredentials is only called when no scopes and an + * authUrl (audience) is suppled. + * + * @return void + */ + public function useJwtAccessWithScope() + { + $this->useJwtAccessWithScope = true; + } + + /** + * @param callable $httpHandler + * + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_in + * @type string $token_type + * } + */ + public function fetchAuthToken(callable $httpHandler = null) + { + if ($this->useSelfSignedJwt()) { + $jwtCreds = $this->createJwtAccessCredentials(); + + $accessToken = $jwtCreds->fetchAuthToken($httpHandler); + + if ($lastReceivedToken = $jwtCreds->getLastReceivedToken()) { + // Keep self-signed JWTs in memory as the last received token + $this->lastReceivedJwtAccessToken = $lastReceivedToken; + } + + return $accessToken; + } + return $this->auth->fetchAuthToken($httpHandler); + } + + /** + * @return string + */ + public function getCacheKey() + { + $key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey(); + if ($sub = $this->auth->getSub()) { + $key .= ':' . $sub; + } + + return $key; + } + + /** + * @return array + */ + public function getLastReceivedToken() + { + // If self-signed JWTs are being used, fetch the last received token + // from memory. Else, fetch it from OAuth2 + return $this->useSelfSignedJwt() + ? $this->lastReceivedJwtAccessToken + : $this->auth->getLastReceivedToken(); + } + + /** + * Get the project ID from the service account keyfile. + * + * Returns null if the project ID does not exist in the keyfile. + * + * @param callable $httpHandler Not used by this credentials type. + * @return string|null + */ + public function getProjectId(callable $httpHandler = null) + { + return $this->projectId; + } + + /** + * Updates metadata with the authorization token. + * + * @param array $metadata metadata hashmap + * @param string $authUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * @return array updated metadata hashmap + */ + public function updateMetadata( + $metadata, + $authUri = null, + callable $httpHandler = null + ) { + // scope exists. use oauth implementation + if (!$this->useSelfSignedJwt()) { + return parent::updateMetadata($metadata, $authUri, $httpHandler); + } + + $jwtCreds = $this->createJwtAccessCredentials(); + if ($this->auth->getScope()) { + // Prefer user-provided "scope" to "audience" + $updatedMetadata = $jwtCreds->updateMetadata($metadata, null, $httpHandler); + } else { + $updatedMetadata = $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler); + } + + if ($lastReceivedToken = $jwtCreds->getLastReceivedToken()) { + // Keep self-signed JWTs in memory as the last received token + $this->lastReceivedJwtAccessToken = $lastReceivedToken; + } + + return $updatedMetadata; + } + + /** + * @return ServiceAccountJwtAccessCredentials + */ + private function createJwtAccessCredentials() + { + if (!$this->jwtAccessCredentials) { + // Create credentials for self-signing a JWT (JwtAccess) + $credJson = [ + 'private_key' => $this->auth->getSigningKey(), + 'client_email' => $this->auth->getIssuer(), + ]; + $this->jwtAccessCredentials = new ServiceAccountJwtAccessCredentials( + $credJson, + $this->auth->getScope() + ); + } + + return $this->jwtAccessCredentials; + } + + /** + * @param string $sub an email address account to impersonate, in situations when + * the service account has been delegated domain wide access. + * @return void + */ + public function setSub($sub) + { + $this->auth->setSub($sub); + } + + /** + * Get the client name from the keyfile. + * + * In this case, it returns the keyfile's client_email key. + * + * @param callable $httpHandler Not used by this credentials type. + * @return string + */ + public function getClientName(callable $httpHandler = null) + { + return $this->auth->getIssuer(); + } + + /** + * Get the quota project used for this API request + * + * @return string|null + */ + public function getQuotaProject() + { + return $this->quotaProject; + } + + /** + * Get the universe domain configured in the JSON credential. + * + * @return string + */ + public function getUniverseDomain(): string + { + return $this->universeDomain; + } + + /** + * @return bool + */ + private function useSelfSignedJwt() + { + // When a sub is supplied, the user is using domain-wide delegation, which not available + // with self-signed JWTs + if (null !== $this->auth->getSub()) { + // If we are outside the GDU, we can't use domain-wide delegation + if ($this->getUniverseDomain() !== self::DEFAULT_UNIVERSE_DOMAIN) { + throw new \LogicException(sprintf( + 'Service Account subject is configured for the credential. Domain-wide ' . + 'delegation is not supported in universes other than %s.', + self::DEFAULT_UNIVERSE_DOMAIN + )); + } + return false; + } + + // If claims are set, this call is for "id_tokens" + if ($this->auth->getAdditionalClaims()) { + return false; + } + + // When true, ServiceAccountCredentials will always use JwtAccess for access tokens + if ($this->useJwtAccessWithScope) { + return true; + } + + // If the universe domain is outside the GDU, use JwtAccess for access tokens + if ($this->getUniverseDomain() !== self::DEFAULT_UNIVERSE_DOMAIN) { + return true; + } + + return is_null($this->auth->getScope()); + } +} diff --git a/vendor/google/auth/src/Credentials/ServiceAccountJwtAccessCredentials.php b/vendor/google/auth/src/Credentials/ServiceAccountJwtAccessCredentials.php new file mode 100644 index 0000000..8b2fb94 --- /dev/null +++ b/vendor/google/auth/src/Credentials/ServiceAccountJwtAccessCredentials.php @@ -0,0 +1,212 @@ + $jsonKey JSON credential file path or JSON credentials + * as an associative array + * @param string|string[] $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + */ + public function __construct($jsonKey, $scope = null) + { + if (is_string($jsonKey)) { + if (!file_exists($jsonKey)) { + throw new \InvalidArgumentException('file does not exist'); + } + $jsonKeyStream = file_get_contents($jsonKey); + if (!$jsonKey = json_decode((string) $jsonKeyStream, true)) { + throw new \LogicException('invalid json for auth config'); + } + } + if (!array_key_exists('client_email', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the client_email field' + ); + } + if (!array_key_exists('private_key', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the private_key field' + ); + } + if (array_key_exists('quota_project_id', $jsonKey)) { + $this->quotaProject = (string) $jsonKey['quota_project_id']; + } + $this->auth = new OAuth2([ + 'issuer' => $jsonKey['client_email'], + 'sub' => $jsonKey['client_email'], + 'signingAlgorithm' => 'RS256', + 'signingKey' => $jsonKey['private_key'], + 'scope' => $scope, + ]); + + $this->projectId = $jsonKey['project_id'] ?? null; + } + + /** + * Updates metadata with the authorization token. + * + * @param array $metadata metadata hashmap + * @param string $authUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * @return array updated metadata hashmap + */ + public function updateMetadata( + $metadata, + $authUri = null, + callable $httpHandler = null + ) { + $scope = $this->auth->getScope(); + if (empty($authUri) && empty($scope)) { + return $metadata; + } + + $this->auth->setAudience($authUri); + + return parent::updateMetadata($metadata, $authUri, $httpHandler); + } + + /** + * Implements FetchAuthTokenInterface#fetchAuthToken. + * + * @param callable $httpHandler + * + * @return null|array{access_token:string} A set of auth related metadata + */ + public function fetchAuthToken(callable $httpHandler = null) + { + $audience = $this->auth->getAudience(); + $scope = $this->auth->getScope(); + if (empty($audience) && empty($scope)) { + return null; + } + + if (!empty($audience) && !empty($scope)) { + throw new \UnexpectedValueException( + 'Cannot sign both audience and scope in JwtAccess' + ); + } + + $access_token = $this->auth->toJwt(); + + // Set the self-signed access token in OAuth2 for getLastReceivedToken + $this->auth->setAccessToken($access_token); + + return [ + 'access_token' => $access_token, + 'expires_in' => $this->auth->getExpiry(), + 'token_type' => 'Bearer' + ]; + } + + /** + * @return string + */ + public function getCacheKey() + { + return $this->auth->getCacheKey(); + } + + /** + * @return array + */ + public function getLastReceivedToken() + { + return $this->auth->getLastReceivedToken(); + } + + /** + * Get the project ID from the service account keyfile. + * + * Returns null if the project ID does not exist in the keyfile. + * + * @param callable $httpHandler Not used by this credentials type. + * @return string|null + */ + public function getProjectId(callable $httpHandler = null) + { + return $this->projectId; + } + + /** + * Get the client name from the keyfile. + * + * In this case, it returns the keyfile's client_email key. + * + * @param callable $httpHandler Not used by this credentials type. + * @return string + */ + public function getClientName(callable $httpHandler = null) + { + return $this->auth->getIssuer(); + } + + /** + * Get the quota project used for this API request + * + * @return string|null + */ + public function getQuotaProject() + { + return $this->quotaProject; + } +} diff --git a/vendor/google/auth/src/Credentials/UserRefreshCredentials.php b/vendor/google/auth/src/Credentials/UserRefreshCredentials.php new file mode 100644 index 0000000..e2f32d8 --- /dev/null +++ b/vendor/google/auth/src/Credentials/UserRefreshCredentials.php @@ -0,0 +1,152 @@ + $jsonKey JSON credential file path or JSON credentials + * as an associative array + */ + public function __construct( + $scope, + $jsonKey + ) { + if (is_string($jsonKey)) { + if (!file_exists($jsonKey)) { + throw new \InvalidArgumentException('file does not exist'); + } + $json = file_get_contents($jsonKey); + if (!$jsonKey = json_decode((string) $json, true)) { + throw new \LogicException('invalid json for auth config'); + } + } + if (!array_key_exists('client_id', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the client_id field' + ); + } + if (!array_key_exists('client_secret', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the client_secret field' + ); + } + if (!array_key_exists('refresh_token', $jsonKey)) { + throw new \InvalidArgumentException( + 'json key is missing the refresh_token field' + ); + } + $this->auth = new OAuth2([ + 'clientId' => $jsonKey['client_id'], + 'clientSecret' => $jsonKey['client_secret'], + 'refresh_token' => $jsonKey['refresh_token'], + 'scope' => $scope, + 'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI, + ]); + if (array_key_exists('quota_project_id', $jsonKey)) { + $this->quotaProject = (string) $jsonKey['quota_project_id']; + } + } + + /** + * @param callable $httpHandler + * + * @return array { + * A set of auth related metadata, containing the following + * + * @type string $access_token + * @type int $expires_in + * @type string $scope + * @type string $token_type + * @type string $id_token + * } + */ + public function fetchAuthToken(callable $httpHandler = null) + { + return $this->auth->fetchAuthToken($httpHandler); + } + + /** + * @return string + */ + public function getCacheKey() + { + return $this->auth->getClientId() . ':' . $this->auth->getCacheKey(); + } + + /** + * @return array + */ + public function getLastReceivedToken() + { + return $this->auth->getLastReceivedToken(); + } + + /** + * Get the quota project used for this API request + * + * @return string|null + */ + public function getQuotaProject() + { + return $this->quotaProject; + } + + /** + * Get the granted scopes (if they exist) for the last fetched token. + * + * @return string|null + */ + public function getGrantedScope() + { + return $this->auth->getGrantedScope(); + } +} diff --git a/vendor/google/auth/src/CredentialsLoader.php b/vendor/google/auth/src/CredentialsLoader.php new file mode 100644 index 0000000..746b957 --- /dev/null +++ b/vendor/google/auth/src/CredentialsLoader.php @@ -0,0 +1,288 @@ +|null JSON key | null + */ + public static function fromEnv() + { + $path = getenv(self::ENV_VAR); + if (empty($path)) { + return null; + } + if (!file_exists($path)) { + $cause = 'file ' . $path . ' does not exist'; + throw new \DomainException(self::unableToReadEnv($cause)); + } + $jsonKey = file_get_contents($path); + return json_decode((string) $jsonKey, true); + } + + /** + * Load a JSON key from a well known path. + * + * The well known path is OS dependent: + * + * * windows: %APPDATA%/gcloud/application_default_credentials.json + * * others: $HOME/.config/gcloud/application_default_credentials.json + * + * If the file does not exist, this returns null. + * + * @return array|null JSON key | null + */ + public static function fromWellKnownFile() + { + $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME'; + $path = [getenv($rootEnv)]; + if (!self::isOnWindows()) { + $path[] = self::NON_WINDOWS_WELL_KNOWN_PATH_BASE; + } + $path[] = self::WELL_KNOWN_PATH; + $path = implode(DIRECTORY_SEPARATOR, $path); + if (!file_exists($path)) { + return null; + } + $jsonKey = file_get_contents($path); + return json_decode((string) $jsonKey, true); + } + + /** + * Create a new Credentials instance. + * + * @param string|string[] $scope the scope of the access request, expressed + * either as an Array or as a space-delimited String. + * @param array $jsonKey the JSON credentials. + * @param string|string[] $defaultScope The default scope to use if no + * user-defined scopes exist, expressed either as an Array or as a + * space-delimited string. + * + * @return ServiceAccountCredentials|UserRefreshCredentials|ImpersonatedServiceAccountCredentials|ExternalAccountCredentials + */ + public static function makeCredentials( + $scope, + array $jsonKey, + $defaultScope = null + ) { + if (!array_key_exists('type', $jsonKey)) { + throw new \InvalidArgumentException('json key is missing the type field'); + } + + if ($jsonKey['type'] == 'service_account') { + // Do not pass $defaultScope to ServiceAccountCredentials + return new ServiceAccountCredentials($scope, $jsonKey); + } + + if ($jsonKey['type'] == 'authorized_user') { + $anyScope = $scope ?: $defaultScope; + return new UserRefreshCredentials($anyScope, $jsonKey); + } + + if ($jsonKey['type'] == 'impersonated_service_account') { + $anyScope = $scope ?: $defaultScope; + return new ImpersonatedServiceAccountCredentials($anyScope, $jsonKey); + } + + if ($jsonKey['type'] == 'external_account') { + $anyScope = $scope ?: $defaultScope; + return new ExternalAccountCredentials($anyScope, $jsonKey); + } + + throw new \InvalidArgumentException('invalid value in the type field'); + } + + /** + * Create an authorized HTTP Client from an instance of FetchAuthTokenInterface. + * + * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token + * @param array $httpClientOptions (optional) Array of request options to apply. + * @param callable $httpHandler (optional) http client to fetch the token. + * @param callable $tokenCallback (optional) function to be called when a new token is fetched. + * @return \GuzzleHttp\Client + */ + public static function makeHttpClient( + FetchAuthTokenInterface $fetcher, + array $httpClientOptions = [], + callable $httpHandler = null, + callable $tokenCallback = null + ) { + $middleware = new Middleware\AuthTokenMiddleware( + $fetcher, + $httpHandler, + $tokenCallback + ); + $stack = \GuzzleHttp\HandlerStack::create(); + $stack->push($middleware); + + return new \GuzzleHttp\Client([ + 'handler' => $stack, + 'auth' => 'google_auth', + ] + $httpClientOptions); + } + + /** + * Create a new instance of InsecureCredentials. + * + * @return InsecureCredentials + */ + public static function makeInsecureCredentials() + { + return new InsecureCredentials(); + } + + /** + * Fetch a quota project from the environment variable + * GOOGLE_CLOUD_QUOTA_PROJECT. Return null if + * GOOGLE_CLOUD_QUOTA_PROJECT is not specified. + * + * @return string|null + */ + public static function quotaProjectFromEnv() + { + return getenv(self::QUOTA_PROJECT_ENV_VAR) ?: null; + } + + /** + * Gets a callable which returns the default device certification. + * + * @throws UnexpectedValueException + * @return callable|null + */ + public static function getDefaultClientCertSource() + { + if (!$clientCertSourceJson = self::loadDefaultClientCertSourceFile()) { + return null; + } + $clientCertSourceCmd = $clientCertSourceJson['cert_provider_command']; + + return function () use ($clientCertSourceCmd) { + $cmd = array_map('escapeshellarg', $clientCertSourceCmd); + exec(implode(' ', $cmd), $output, $returnVar); + + if (0 === $returnVar) { + return implode(PHP_EOL, $output); + } + throw new RuntimeException( + '"cert_provider_command" failed with a nonzero exit code' + ); + }; + } + + /** + * Determines whether or not the default device certificate should be loaded. + * + * @return bool + */ + public static function shouldLoadClientCertSource() + { + return filter_var(getenv(self::MTLS_CERT_ENV_VAR), FILTER_VALIDATE_BOOLEAN); + } + + /** + * @return array{cert_provider_command:string[]}|null + */ + private static function loadDefaultClientCertSourceFile() + { + $rootEnv = self::isOnWindows() ? 'APPDATA' : 'HOME'; + $path = sprintf('%s/%s', getenv($rootEnv), self::MTLS_WELL_KNOWN_PATH); + if (!file_exists($path)) { + return null; + } + $jsonKey = file_get_contents($path); + $clientCertSourceJson = json_decode((string) $jsonKey, true); + if (!$clientCertSourceJson) { + throw new UnexpectedValueException('Invalid client cert source JSON'); + } + if (!isset($clientCertSourceJson['cert_provider_command'])) { + throw new UnexpectedValueException( + 'cert source requires "cert_provider_command"' + ); + } + if (!is_array($clientCertSourceJson['cert_provider_command'])) { + throw new UnexpectedValueException( + 'cert source expects "cert_provider_command" to be an array' + ); + } + return $clientCertSourceJson; + } + + /** + * Get the universe domain from the credential. Defaults to "googleapis.com" + * for all credential types which do not support universe domain. + * + * @return string + */ + public function getUniverseDomain(): string + { + return self::DEFAULT_UNIVERSE_DOMAIN; + } +} diff --git a/vendor/google/auth/src/ExternalAccountCredentialSourceInterface.php b/vendor/google/auth/src/ExternalAccountCredentialSourceInterface.php new file mode 100644 index 0000000..b4d00f8 --- /dev/null +++ b/vendor/google/auth/src/ExternalAccountCredentialSourceInterface.php @@ -0,0 +1,23 @@ + $cacheConfig Configuration for the cache + * @param CacheItemPoolInterface $cache + */ + public function __construct( + FetchAuthTokenInterface $fetcher, + array $cacheConfig = null, + CacheItemPoolInterface $cache + ) { + $this->fetcher = $fetcher; + $this->cache = $cache; + $this->cacheConfig = array_merge([ + 'lifetime' => 1500, + 'prefix' => '', + ], (array) $cacheConfig); + } + + /** + * @return FetchAuthTokenInterface + */ + public function getFetcher() + { + return $this->fetcher; + } + + /** + * Implements FetchAuthTokenInterface#fetchAuthToken. + * + * Checks the cache for a valid auth token and fetches the auth tokens + * from the supplied fetcher. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return array the response + * @throws \Exception + */ + public function fetchAuthToken(callable $httpHandler = null) + { + if ($cached = $this->fetchAuthTokenFromCache()) { + return $cached; + } + + $auth_token = $this->fetcher->fetchAuthToken($httpHandler); + + $this->saveAuthTokenInCache($auth_token); + + return $auth_token; + } + + /** + * @return string + */ + public function getCacheKey() + { + return $this->getFullCacheKey($this->fetcher->getCacheKey()); + } + + /** + * @return array|null + */ + public function getLastReceivedToken() + { + return $this->fetcher->getLastReceivedToken(); + } + + /** + * Get the client name from the fetcher. + * + * @param callable $httpHandler An HTTP handler to deliver PSR7 requests. + * @return string + */ + public function getClientName(callable $httpHandler = null) + { + if (!$this->fetcher instanceof SignBlobInterface) { + throw new \RuntimeException( + 'Credentials fetcher does not implement ' . + 'Google\Auth\SignBlobInterface' + ); + } + + return $this->fetcher->getClientName($httpHandler); + } + + /** + * Sign a blob using the fetcher. + * + * @param string $stringToSign The string to sign. + * @param bool $forceOpenSsl Require use of OpenSSL for local signing. Does + * not apply to signing done using external services. **Defaults to** + * `false`. + * @return string The resulting signature. + * @throws \RuntimeException If the fetcher does not implement + * `Google\Auth\SignBlobInterface`. + */ + public function signBlob($stringToSign, $forceOpenSsl = false) + { + if (!$this->fetcher instanceof SignBlobInterface) { + throw new \RuntimeException( + 'Credentials fetcher does not implement ' . + 'Google\Auth\SignBlobInterface' + ); + } + + // Pass the access token from cache for credentials that sign blobs + // using the IAM API. This saves a call to fetch an access token when a + // cached token exists. + if ($this->fetcher instanceof Credentials\GCECredentials + || $this->fetcher instanceof Credentials\ImpersonatedServiceAccountCredentials + ) { + $cached = $this->fetchAuthTokenFromCache(); + $accessToken = $cached['access_token'] ?? null; + return $this->fetcher->signBlob($stringToSign, $forceOpenSsl, $accessToken); + } + + return $this->fetcher->signBlob($stringToSign, $forceOpenSsl); + } + + /** + * Get the quota project used for this API request from the credentials + * fetcher. + * + * @return string|null + */ + public function getQuotaProject() + { + if ($this->fetcher instanceof GetQuotaProjectInterface) { + return $this->fetcher->getQuotaProject(); + } + + return null; + } + + /* + * Get the Project ID from the fetcher. + * + * @param callable $httpHandler Callback which delivers psr7 request + * @return string|null + * @throws \RuntimeException If the fetcher does not implement + * `Google\Auth\ProvidesProjectIdInterface`. + */ + public function getProjectId(callable $httpHandler = null) + { + if (!$this->fetcher instanceof ProjectIdProviderInterface) { + throw new \RuntimeException( + 'Credentials fetcher does not implement ' . + 'Google\Auth\ProvidesProjectIdInterface' + ); + } + + // Pass the access token from cache for credentials that require an + // access token to fetch the project ID. This saves a call to fetch an + // access token when a cached token exists. + if ($this->fetcher instanceof Credentials\ExternalAccountCredentials) { + $cached = $this->fetchAuthTokenFromCache(); + $accessToken = $cached['access_token'] ?? null; + return $this->fetcher->getProjectId($httpHandler, $accessToken); + } + + return $this->fetcher->getProjectId($httpHandler); + } + + /* + * Get the Universe Domain from the fetcher. + * + * @return string + */ + public function getUniverseDomain(): string + { + if ($this->fetcher instanceof GetUniverseDomainInterface) { + return $this->fetcher->getUniverseDomain(); + } + + return GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + } + + /** + * Updates metadata with the authorization token. + * + * @param array $metadata metadata hashmap + * @param string $authUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * @return array updated metadata hashmap + * @throws \RuntimeException If the fetcher does not implement + * `Google\Auth\UpdateMetadataInterface`. + */ + public function updateMetadata( + $metadata, + $authUri = null, + callable $httpHandler = null + ) { + if (!$this->fetcher instanceof UpdateMetadataInterface) { + throw new \RuntimeException( + 'Credentials fetcher does not implement ' . + 'Google\Auth\UpdateMetadataInterface' + ); + } + + $cached = $this->fetchAuthTokenFromCache($authUri); + if ($cached) { + // Set the access token in the `Authorization` metadata header so + // the downstream call to updateMetadata know they don't need to + // fetch another token. + if (isset($cached['access_token'])) { + $metadata[self::AUTH_METADATA_KEY] = [ + 'Bearer ' . $cached['access_token'] + ]; + } elseif (isset($cached['id_token'])) { + $metadata[self::AUTH_METADATA_KEY] = [ + 'Bearer ' . $cached['id_token'] + ]; + } + } + + $newMetadata = $this->fetcher->updateMetadata( + $metadata, + $authUri, + $httpHandler + ); + + if (!$cached && $token = $this->fetcher->getLastReceivedToken()) { + $this->saveAuthTokenInCache($token, $authUri); + } + + return $newMetadata; + } + + /** + * @param string|null $authUri + * @return array|null + */ + private function fetchAuthTokenFromCache($authUri = null) + { + // Use the cached value if its available. + // + // TODO: correct caching; update the call to setCachedValue to set the expiry + // to the value returned with the auth token. + // + // TODO: correct caching; enable the cache to be cleared. + + // if $authUri is set, use it as the cache key + $cacheKey = $authUri + ? $this->getFullCacheKey($authUri) + : $this->fetcher->getCacheKey(); + + $cached = $this->getCachedValue($cacheKey); + if (is_array($cached)) { + if (empty($cached['expires_at'])) { + // If there is no expiration data, assume token is not expired. + // (for JwtAccess and ID tokens) + return $cached; + } + if ((time() + $this->eagerRefreshThresholdSeconds) < $cached['expires_at']) { + // access token is not expired + return $cached; + } + } + + return null; + } + + /** + * @param array $authToken + * @param string|null $authUri + * @return void + */ + private function saveAuthTokenInCache($authToken, $authUri = null) + { + if (isset($authToken['access_token']) || + isset($authToken['id_token'])) { + // if $authUri is set, use it as the cache key + $cacheKey = $authUri + ? $this->getFullCacheKey($authUri) + : $this->fetcher->getCacheKey(); + + $this->setCachedValue($cacheKey, $authToken); + } + } +} diff --git a/vendor/google/auth/src/FetchAuthTokenInterface.php b/vendor/google/auth/src/FetchAuthTokenInterface.php new file mode 100644 index 0000000..6465955 --- /dev/null +++ b/vendor/google/auth/src/FetchAuthTokenInterface.php @@ -0,0 +1,54 @@ + a hash of auth tokens + */ + public function fetchAuthToken(callable $httpHandler = null); + + /** + * Obtains a key that can used to cache the results of #fetchAuthToken. + * + * If the value is empty, the auth token is not cached. + * + * @return string a key that may be used to cache the auth token. + */ + public function getCacheKey(); + + /** + * Returns an associative array with the token and + * expiration time. + * + * @return null|array { + * The last received access token. + * + * @type string $access_token The access token string. + * @type int $expires_at The time the token expires as a UNIX timestamp. + * } + */ + public function getLastReceivedToken(); +} diff --git a/vendor/google/auth/src/GCECache.php b/vendor/google/auth/src/GCECache.php new file mode 100644 index 0000000..804abdb --- /dev/null +++ b/vendor/google/auth/src/GCECache.php @@ -0,0 +1,82 @@ + $cacheConfig Configuration for the cache + * @param CacheItemPoolInterface $cache + */ + public function __construct( + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $this->cache = $cache; + $this->cacheConfig = array_merge([ + 'lifetime' => 1500, + 'prefix' => '', + ], (array) $cacheConfig); + } + + /** + * Caches the result of onGce so the metadata server is not called multiple + * times. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return bool True if this a GCEInstance, false otherwise + */ + public function onGce(callable $httpHandler = null) + { + if (is_null($this->cache)) { + return GCECredentials::onGce($httpHandler); + } + + $cacheKey = self::GCE_CACHE_KEY; + $onGce = $this->getCachedValue($cacheKey); + + if (is_null($onGce)) { + $onGce = GCECredentials::onGce($httpHandler); + $this->setCachedValue($cacheKey, $onGce); + } + + return $onGce; + } +} diff --git a/vendor/google/auth/src/GetQuotaProjectInterface.php b/vendor/google/auth/src/GetQuotaProjectInterface.php new file mode 100644 index 0000000..517f062 --- /dev/null +++ b/vendor/google/auth/src/GetQuotaProjectInterface.php @@ -0,0 +1,33 @@ +client = $client; + } + + /** + * Accepts a PSR-7 request and an array of options and returns a PSR-7 response. + * + * @param RequestInterface $request + * @param array $options + * @return ResponseInterface + */ + public function __invoke(RequestInterface $request, array $options = []) + { + return $this->client->send($request, $options); + } + + /** + * Accepts a PSR-7 request and an array of options and returns a PromiseInterface + * + * @param RequestInterface $request + * @param array $options + * + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function async(RequestInterface $request, array $options = []) + { + return $this->client->sendAsync($request, $options); + } +} diff --git a/vendor/google/auth/src/HttpHandler/Guzzle7HttpHandler.php b/vendor/google/auth/src/HttpHandler/Guzzle7HttpHandler.php new file mode 100644 index 0000000..e84f660 --- /dev/null +++ b/vendor/google/auth/src/HttpHandler/Guzzle7HttpHandler.php @@ -0,0 +1,21 @@ +remove('http_errors'); + $stack->unshift(Middleware::httpErrors($bodySummarizer), 'http_errors'); + } + $client = new Client(['handler' => $stack]); + } + + $version = null; + if (defined('GuzzleHttp\ClientInterface::MAJOR_VERSION')) { + $version = ClientInterface::MAJOR_VERSION; + } elseif (defined('GuzzleHttp\ClientInterface::VERSION')) { + $version = (int) substr(ClientInterface::VERSION, 0, 1); + } + + switch ($version) { + case 6: + return new Guzzle6HttpHandler($client); + case 7: + return new Guzzle7HttpHandler($client); + default: + throw new \Exception('Version not supported'); + } + } +} diff --git a/vendor/google/auth/src/Iam.php b/vendor/google/auth/src/Iam.php new file mode 100644 index 0000000..943ecf2 --- /dev/null +++ b/vendor/google/auth/src/Iam.php @@ -0,0 +1,100 @@ +httpHandler = $httpHandler + ?: HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + + /** + * Sign a string using the IAM signBlob API. + * + * Note that signing using IAM requires your service account to have the + * `iam.serviceAccounts.signBlob` permission, part of the "Service Account + * Token Creator" IAM role. + * + * @param string $email The service account email. + * @param string $accessToken An access token from the service account. + * @param string $stringToSign The string to be signed. + * @param array $delegates [optional] A list of service account emails to + * add to the delegate chain. If omitted, the value of `$email` will + * be used. + * @return string The signed string, base64-encoded. + */ + public function signBlob($email, $accessToken, $stringToSign, array $delegates = []) + { + $httpHandler = $this->httpHandler; + $name = sprintf(self::SERVICE_ACCOUNT_NAME, $email); + $uri = self::IAM_API_ROOT . '/' . sprintf(self::SIGN_BLOB_PATH, $name); + + if ($delegates) { + foreach ($delegates as &$delegate) { + $delegate = sprintf(self::SERVICE_ACCOUNT_NAME, $delegate); + } + } else { + $delegates = [$name]; + } + + $body = [ + 'delegates' => $delegates, + 'payload' => base64_encode($stringToSign), + ]; + + $headers = [ + 'Authorization' => 'Bearer ' . $accessToken + ]; + + $request = new Psr7\Request( + 'POST', + $uri, + $headers, + Utils::streamFor(json_encode($body)) + ); + + $res = $httpHandler($request); + $body = json_decode((string) $res->getBody(), true); + + return $body['signedBlob']; + } +} diff --git a/vendor/google/auth/src/IamSignerTrait.php b/vendor/google/auth/src/IamSignerTrait.php new file mode 100644 index 0000000..9de18b3 --- /dev/null +++ b/vendor/google/auth/src/IamSignerTrait.php @@ -0,0 +1,67 @@ +iam ?: new Iam($httpHandler); + + $email = $this->getClientName($httpHandler); + + if (is_null($accessToken)) { + $previousToken = $this->getLastReceivedToken(); + $accessToken = $previousToken + ? $previousToken['access_token'] + : $this->fetchAuthToken($httpHandler)['access_token']; + } + + return $signer->signBlob($email, $accessToken, $stringToSign); + } +} diff --git a/vendor/google/auth/src/Middleware/AuthTokenMiddleware.php b/vendor/google/auth/src/Middleware/AuthTokenMiddleware.php new file mode 100644 index 0000000..798766e --- /dev/null +++ b/vendor/google/auth/src/Middleware/AuthTokenMiddleware.php @@ -0,0 +1,162 @@ +' + */ +class AuthTokenMiddleware +{ + /** + * @var callable + */ + private $httpHandler; + + /** + * It must be an implementation of FetchAuthTokenInterface. + * It may also implement UpdateMetadataInterface allowing direct + * retrieval of auth related headers + * @var FetchAuthTokenInterface + */ + private $fetcher; + + /** + * @var ?callable + */ + private $tokenCallback; + + /** + * Creates a new AuthTokenMiddleware. + * + * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token + * @param callable $httpHandler (optional) callback which delivers psr7 request + * @param callable $tokenCallback (optional) function to be called when a new token is fetched. + */ + public function __construct( + FetchAuthTokenInterface $fetcher, + callable $httpHandler = null, + callable $tokenCallback = null + ) { + $this->fetcher = $fetcher; + $this->httpHandler = $httpHandler; + $this->tokenCallback = $tokenCallback; + } + + /** + * Updates the request with an Authorization header when auth is 'google_auth'. + * + * use Google\Auth\Middleware\AuthTokenMiddleware; + * use Google\Auth\OAuth2; + * use GuzzleHttp\Client; + * use GuzzleHttp\HandlerStack; + * + * $config = [...]; + * $oauth2 = new OAuth2($config) + * $middleware = new AuthTokenMiddleware($oauth2); + * $stack = HandlerStack::create(); + * $stack->push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'auth' => 'google_auth' // authorize all requests + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + * + * @param callable $handler + * @return \Closure + */ + public function __invoke(callable $handler) + { + return function (RequestInterface $request, array $options) use ($handler) { + // Requests using "auth"="google_auth" will be authorized. + if (!isset($options['auth']) || $options['auth'] !== 'google_auth') { + return $handler($request, $options); + } + + $request = $this->addAuthHeaders($request); + + if ($quotaProject = $this->getQuotaProject()) { + $request = $request->withHeader( + GetQuotaProjectInterface::X_GOOG_USER_PROJECT_HEADER, + $quotaProject + ); + } + + return $handler($request, $options); + }; + } + + /** + * Adds auth related headers to the request. + * + * @param RequestInterface $request + * @return RequestInterface + */ + private function addAuthHeaders(RequestInterface $request) + { + if (!$this->fetcher instanceof UpdateMetadataInterface || + ($this->fetcher instanceof FetchAuthTokenCache && + !$this->fetcher->getFetcher() instanceof UpdateMetadataInterface) + ) { + $token = $this->fetcher->fetchAuthToken(); + $request = $request->withHeader( + 'authorization', 'Bearer ' . ($token['access_token'] ?? $token['id_token'] ?? '') + ); + } else { + $headers = $this->fetcher->updateMetadata($request->getHeaders(), null, $this->httpHandler); + $request = Utils::modifyRequest($request, ['set_headers' => $headers]); + } + + if ($this->tokenCallback && ($token = $this->fetcher->getLastReceivedToken())) { + if (array_key_exists('access_token', $token)) { + call_user_func($this->tokenCallback, $this->fetcher->getCacheKey(), $token['access_token']); + } + } + + return $request; + } + + /** + * @return string|null + */ + private function getQuotaProject() + { + if ($this->fetcher instanceof GetQuotaProjectInterface) { + return $this->fetcher->getQuotaProject(); + } + + return null; + } +} diff --git a/vendor/google/auth/src/Middleware/ProxyAuthTokenMiddleware.php b/vendor/google/auth/src/Middleware/ProxyAuthTokenMiddleware.php new file mode 100644 index 0000000..0f9ee42 --- /dev/null +++ b/vendor/google/auth/src/Middleware/ProxyAuthTokenMiddleware.php @@ -0,0 +1,155 @@ +' + */ +class ProxyAuthTokenMiddleware +{ + /** + * @var callable + */ + private $httpHandler; + + /** + * @var FetchAuthTokenInterface + */ + private $fetcher; + + /** + * @var ?callable + */ + private $tokenCallback; + + /** + * Creates a new ProxyAuthTokenMiddleware. + * + * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token + * @param callable $httpHandler (optional) callback which delivers psr7 request + * @param callable $tokenCallback (optional) function to be called when a new token is fetched. + */ + public function __construct( + FetchAuthTokenInterface $fetcher, + callable $httpHandler = null, + callable $tokenCallback = null + ) { + $this->fetcher = $fetcher; + $this->httpHandler = $httpHandler; + $this->tokenCallback = $tokenCallback; + } + + /** + * Updates the request with an Authorization header when auth is 'google_auth'. + * + * use Google\Auth\Middleware\ProxyAuthTokenMiddleware; + * use Google\Auth\OAuth2; + * use GuzzleHttp\Client; + * use GuzzleHttp\HandlerStack; + * + * $config = [...]; + * $oauth2 = new OAuth2($config) + * $middleware = new ProxyAuthTokenMiddleware($oauth2); + * $stack = HandlerStack::create(); + * $stack->push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'proxy_auth' => 'google_auth' // authorize all requests + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + * + * @param callable $handler + * @return \Closure + */ + public function __invoke(callable $handler) + { + return function (RequestInterface $request, array $options) use ($handler) { + // Requests using "proxy_auth"="google_auth" will be authorized. + if (!isset($options['proxy_auth']) || $options['proxy_auth'] !== 'google_auth') { + return $handler($request, $options); + } + + $request = $request->withHeader('proxy-authorization', 'Bearer ' . $this->fetchToken()); + + if ($quotaProject = $this->getQuotaProject()) { + $request = $request->withHeader( + GetQuotaProjectInterface::X_GOOG_USER_PROJECT_HEADER, + $quotaProject + ); + } + + return $handler($request, $options); + }; + } + + /** + * Call fetcher to fetch the token. + * + * @return string|null + */ + private function fetchToken() + { + $auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler); + + if (array_key_exists('access_token', $auth_tokens)) { + // notify the callback if applicable + if ($this->tokenCallback) { + call_user_func( + $this->tokenCallback, + $this->fetcher->getCacheKey(), + $auth_tokens['access_token'] + ); + } + + return $auth_tokens['access_token']; + } + + if (array_key_exists('id_token', $auth_tokens)) { + return $auth_tokens['id_token']; + } + + return null; + } + + /** + * @return string|null; + */ + private function getQuotaProject() + { + if ($this->fetcher instanceof GetQuotaProjectInterface) { + return $this->fetcher->getQuotaProject(); + } + + return null; + } +} diff --git a/vendor/google/auth/src/Middleware/ScopedAccessTokenMiddleware.php b/vendor/google/auth/src/Middleware/ScopedAccessTokenMiddleware.php new file mode 100644 index 0000000..8bb1d7a --- /dev/null +++ b/vendor/google/auth/src/Middleware/ScopedAccessTokenMiddleware.php @@ -0,0 +1,165 @@ +' + */ +class ScopedAccessTokenMiddleware +{ + use CacheTrait; + + const DEFAULT_CACHE_LIFETIME = 1500; + + /** + * @var callable + */ + private $tokenFunc; + + /** + * @var array|string + */ + private $scopes; + + /** + * Creates a new ScopedAccessTokenMiddleware. + * + * @param callable $tokenFunc a token generator function + * @param array|string $scopes the token authentication scopes + * @param array $cacheConfig configuration for the cache when it's present + * @param CacheItemPoolInterface $cache an implementation of CacheItemPoolInterface + */ + public function __construct( + callable $tokenFunc, + $scopes, + array $cacheConfig = null, + CacheItemPoolInterface $cache = null + ) { + $this->tokenFunc = $tokenFunc; + if (!(is_string($scopes) || is_array($scopes))) { + throw new \InvalidArgumentException( + 'wants scope should be string or array' + ); + } + $this->scopes = $scopes; + + if (!is_null($cache)) { + $this->cache = $cache; + $this->cacheConfig = array_merge([ + 'lifetime' => self::DEFAULT_CACHE_LIFETIME, + 'prefix' => '', + ], $cacheConfig); + } + } + + /** + * Updates the request with an Authorization header when auth is 'scoped'. + * + * E.g this could be used to authenticate using the AppEngine + * AppIdentityService. + * + * use google\appengine\api\app_identity\AppIdentityService; + * use Google\Auth\Middleware\ScopedAccessTokenMiddleware; + * use GuzzleHttp\Client; + * use GuzzleHttp\HandlerStack; + * + * $scope = 'https://www.googleapis.com/auth/taskqueue' + * $middleware = new ScopedAccessTokenMiddleware( + * 'AppIdentityService::getAccessToken', + * $scope, + * [ 'prefix' => 'Google\Auth\ScopedAccessToken::' ], + * $cache = new Memcache() + * ); + * $stack = HandlerStack::create(); + * $stack->push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/', + * 'auth' => 'scoped' // authorize all requests + * ]); + * + * $res = $client->get('myproject/taskqueues/myqueue'); + * + * @param callable $handler + * @return \Closure + */ + public function __invoke(callable $handler) + { + return function (RequestInterface $request, array $options) use ($handler) { + // Requests using "auth"="scoped" will be authorized. + if (!isset($options['auth']) || $options['auth'] !== 'scoped') { + return $handler($request, $options); + } + + $request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken()); + + return $handler($request, $options); + }; + } + + /** + * @return string + */ + private function getCacheKey() + { + $key = null; + + if (is_string($this->scopes)) { + $key .= $this->scopes; + } elseif (is_array($this->scopes)) { + $key .= implode(':', $this->scopes); + } + + return $key; + } + + /** + * Determine if token is available in the cache, if not call tokenFunc to + * fetch it. + * + * @return string + */ + private function fetchToken() + { + $cacheKey = $this->getCacheKey(); + $cached = $this->getCachedValue($cacheKey); + + if (!empty($cached)) { + return $cached; + } + + $token = call_user_func($this->tokenFunc, $this->scopes); + $this->setCachedValue($cacheKey, $token); + + return $token; + } +} diff --git a/vendor/google/auth/src/Middleware/SimpleMiddleware.php b/vendor/google/auth/src/Middleware/SimpleMiddleware.php new file mode 100644 index 0000000..6940430 --- /dev/null +++ b/vendor/google/auth/src/Middleware/SimpleMiddleware.php @@ -0,0 +1,92 @@ + + */ + private $config; + + /** + * Create a new Simple plugin. + * + * The configuration array expects one option + * - key: required, otherwise InvalidArgumentException is thrown + * + * @param array $config Configuration array + */ + public function __construct(array $config) + { + if (!isset($config['key'])) { + throw new \InvalidArgumentException('requires a key to have been set'); + } + + $this->config = array_merge(['key' => null], $config); + } + + /** + * Updates the request query with the developer key if auth is set to simple. + * + * use Google\Auth\Middleware\SimpleMiddleware; + * use GuzzleHttp\Client; + * use GuzzleHttp\HandlerStack; + * + * $my_key = 'is not the same as yours'; + * $middleware = new SimpleMiddleware(['key' => $my_key]); + * $stack = HandlerStack::create(); + * $stack->push($middleware); + * + * $client = new Client([ + * 'handler' => $stack, + * 'base_uri' => 'https://www.googleapis.com/discovery/v1/', + * 'auth' => 'simple' + * ]); + * + * $res = $client->get('drive/v2/rest'); + * + * @param callable $handler + * @return \Closure + */ + public function __invoke(callable $handler) + { + return function (RequestInterface $request, array $options) use ($handler) { + // Requests using "auth"="scoped" will be authorized. + if (!isset($options['auth']) || $options['auth'] !== 'simple') { + return $handler($request, $options); + } + + $query = Query::parse($request->getUri()->getQuery()); + $params = array_merge($query, $this->config); + $uri = $request->getUri()->withQuery(Query::build($params)); + $request = $request->withUri($uri); + + return $handler($request, $options); + }; + } +} diff --git a/vendor/google/auth/src/OAuth2.php b/vendor/google/auth/src/OAuth2.php new file mode 100644 index 0000000..5fc3ba8 --- /dev/null +++ b/vendor/google/auth/src/OAuth2.php @@ -0,0 +1,1798 @@ + + */ + public static $knownSigningAlgorithms = [ + 'HS256', + 'HS512', + 'HS384', + 'RS256', + ]; + + /** + * The well known grant types. + * + * @var array + */ + public static $knownGrantTypes = [ + 'authorization_code', + 'refresh_token', + 'password', + 'client_credentials', + ]; + + /** + * - authorizationUri + * The authorization server's HTTP endpoint capable of + * authenticating the end-user and obtaining authorization. + * + * @var ?UriInterface + */ + private $authorizationUri; + + /** + * - tokenCredentialUri + * The authorization server's HTTP endpoint capable of issuing + * tokens and refreshing expired tokens. + * + * @var UriInterface + */ + private $tokenCredentialUri; + + /** + * The redirection URI used in the initial request. + * + * @var ?string + */ + private $redirectUri; + + /** + * A unique identifier issued to the client to identify itself to the + * authorization server. + * + * @var string + */ + private $clientId; + + /** + * A shared symmetric secret issued by the authorization server, which is + * used to authenticate the client. + * + * @var string + */ + private $clientSecret; + + /** + * The resource owner's username. + * + * @var ?string + */ + private $username; + + /** + * The resource owner's password. + * + * @var ?string + */ + private $password; + + /** + * The scope of the access request, expressed either as an Array or as a + * space-delimited string. + * + * @var ?array + */ + private $scope; + + /** + * An arbitrary string designed to allow the client to maintain state. + * + * @var string + */ + private $state; + + /** + * The authorization code issued to this client. + * + * Only used by the authorization code access grant type. + * + * @var ?string + */ + private $code; + + /** + * The issuer ID when using assertion profile. + * + * @var ?string + */ + private $issuer; + + /** + * The target audience for assertions. + * + * @var string + */ + private $audience; + + /** + * The target sub when issuing assertions. + * + * @var string + */ + private $sub; + + /** + * The number of seconds assertions are valid for. + * + * @var int + */ + private $expiry; + + /** + * The signing key when using assertion profile. + * + * @var ?string + */ + private $signingKey; + + /** + * The signing key id when using assertion profile. Param kid in jwt header + * + * @var string + */ + private $signingKeyId; + + /** + * The signing algorithm when using an assertion profile. + * + * @var ?string + */ + private $signingAlgorithm; + + /** + * The refresh token associated with the access token to be refreshed. + * + * @var ?string + */ + private $refreshToken; + + /** + * The current access token. + * + * @var string + */ + private $accessToken; + + /** + * The current ID token. + * + * @var string + */ + private $idToken; + + /** + * The scopes granted to the current access token + * + * @var string + */ + private $grantedScope; + + /** + * The lifetime in seconds of the current access token. + * + * @var ?int + */ + private $expiresIn; + + /** + * The expiration time of the access token as a number of seconds since the + * unix epoch. + * + * @var ?int + */ + private $expiresAt; + + /** + * The issue time of the access token as a number of seconds since the unix + * epoch. + * + * @var ?int + */ + private $issuedAt; + + /** + * The current grant type. + * + * @var ?string + */ + private $grantType; + + /** + * When using an extension grant type, this is the set of parameters used by + * that extension. + * + * @var array + */ + private $extensionParams; + + /** + * When using the toJwt function, these claims will be added to the JWT + * payload. + * + * @var array + */ + private $additionalClaims; + + /** + * The code verifier for PKCE for OAuth 2.0. When set, the authorization + * URI will contain the Code Challenge and Code Challenge Method querystring + * parameters, and the token URI will contain the Code Verifier parameter. + * + * @see https://datatracker.ietf.org/doc/html/rfc7636 + * @var ?string + */ + private $codeVerifier; + + /** + * For STS requests. + * A URI that indicates the target service or resource where the client + * intends to use the requested security token. + */ + private ?string $resource; + + /** + * For STS requests. + * A fetcher for the "subject_token", which is a security token that + * represents the identity of the party on behalf of whom the request is + * being made. + */ + private ?ExternalAccountCredentialSourceInterface $subjectTokenFetcher; + + /** + * For STS requests. + * An identifier, that indicates the type of the security token in the + * subjectToken parameter. + */ + private ?string $subjectTokenType; + + /** + * For STS requests. + * A security token that represents the identity of the acting party. + */ + private ?string $actorToken; + + /** + * For STS requests. + * An identifier that indicates the type of the security token in the + * actorToken parameter. + */ + private ?string $actorTokenType; + + /** + * From STS response. + * An identifier for the representation of the issued security token. + */ + private ?string $issuedTokenType = null; + + /** + * From STS response. + * An identifier for the representation of the issued security token. + * + * @var array + */ + private array $additionalOptions; + + /** + * Create a new OAuthCredentials. + * + * The configuration array accepts various options + * + * - authorizationUri + * The authorization server's HTTP endpoint capable of + * authenticating the end-user and obtaining authorization. + * + * - tokenCredentialUri + * The authorization server's HTTP endpoint capable of issuing + * tokens and refreshing expired tokens. + * + * - clientId + * A unique identifier issued to the client to identify itself to the + * authorization server. + * + * - clientSecret + * A shared symmetric secret issued by the authorization server, + * which is used to authenticate the client. + * + * - scope + * The scope of the access request, expressed either as an Array + * or as a space-delimited String. + * + * - state + * An arbitrary string designed to allow the client to maintain state. + * + * - redirectUri + * The redirection URI used in the initial request. + * + * - username + * The resource owner's username. + * + * - password + * The resource owner's password. + * + * - issuer + * Issuer ID when using assertion profile + * + * - audience + * Target audience for assertions + * + * - expiry + * Number of seconds assertions are valid for + * + * - signingKey + * Signing key when using assertion profile + * + * - signingKeyId + * Signing key id when using assertion profile + * + * - refreshToken + * The refresh token associated with the access token + * to be refreshed. + * + * - accessToken + * The current access token for this client. + * + * - idToken + * The current ID token for this client. + * + * - extensionParams + * When using an extension grant type, this is the set of parameters used + * by that extension. + * + * - codeVerifier + * The code verifier for PKCE for OAuth 2.0. + * + * - resource + * The target service or resource where the client ntends to use the + * requested security token. + * + * - subjectTokenFetcher + * A fetcher for the "subject_token", which is a security token that + * represents the identity of the party on behalf of whom the request is + * being made. + * + * - subjectTokenType + * An identifier that indicates the type of the security token in the + * subjectToken parameter. + * + * - actorToken + * A security token that represents the identity of the acting party. + * + * - actorTokenType + * An identifier for the representation of the issued security token. + * + * @param array $config Configuration array + */ + public function __construct(array $config) + { + $opts = array_merge([ + 'expiry' => self::DEFAULT_EXPIRY_SECONDS, + 'extensionParams' => [], + 'authorizationUri' => null, + 'redirectUri' => null, + 'tokenCredentialUri' => null, + 'state' => null, + 'username' => null, + 'password' => null, + 'clientId' => null, + 'clientSecret' => null, + 'issuer' => null, + 'sub' => null, + 'audience' => null, + 'signingKey' => null, + 'signingKeyId' => null, + 'signingAlgorithm' => null, + 'scope' => null, + 'additionalClaims' => [], + 'codeVerifier' => null, + 'resource' => null, + 'subjectTokenFetcher' => null, + 'subjectTokenType' => null, + 'actorToken' => null, + 'actorTokenType' => null, + 'additionalOptions' => [], + ], $config); + + $this->setAuthorizationUri($opts['authorizationUri']); + $this->setRedirectUri($opts['redirectUri']); + $this->setTokenCredentialUri($opts['tokenCredentialUri']); + $this->setState($opts['state']); + $this->setUsername($opts['username']); + $this->setPassword($opts['password']); + $this->setClientId($opts['clientId']); + $this->setClientSecret($opts['clientSecret']); + $this->setIssuer($opts['issuer']); + $this->setSub($opts['sub']); + $this->setExpiry($opts['expiry']); + $this->setAudience($opts['audience']); + $this->setSigningKey($opts['signingKey']); + $this->setSigningKeyId($opts['signingKeyId']); + $this->setSigningAlgorithm($opts['signingAlgorithm']); + $this->setScope($opts['scope']); + $this->setExtensionParams($opts['extensionParams']); + $this->setAdditionalClaims($opts['additionalClaims']); + $this->setCodeVerifier($opts['codeVerifier']); + + // for STS + $this->resource = $opts['resource']; + $this->subjectTokenFetcher = $opts['subjectTokenFetcher']; + $this->subjectTokenType = $opts['subjectTokenType']; + $this->actorToken = $opts['actorToken']; + $this->actorTokenType = $opts['actorTokenType']; + $this->additionalOptions = $opts['additionalOptions']; + + $this->updateToken($opts); + } + + /** + * Verifies the idToken if present. + * + * - if none is present, return null + * - if present, but invalid, raises DomainException. + * - otherwise returns the payload in the idtoken as a PHP object. + * + * The behavior of this method varies depending on the version of + * `firebase/php-jwt` you are using. In versions 6.0 and above, you cannot + * provide multiple $allowed_algs, and instead must provide an array of Key + * objects as the $publicKey. + * + * @param string|Key|Key[] $publicKey The public key to use to authenticate the token + * @param string|array $allowed_algs algorithm or array of supported verification algorithms. + * Providing more than one algorithm will throw an exception. + * @throws \DomainException if the token is missing an audience. + * @throws \DomainException if the audience does not match the one set in + * the OAuth2 class instance. + * @throws \UnexpectedValueException If the token is invalid + * @throws \InvalidArgumentException If more than one value for allowed_algs is supplied + * @throws \Firebase\JWT\SignatureInvalidException If the signature is invalid. + * @throws \Firebase\JWT\BeforeValidException If the token is not yet valid. + * @throws \Firebase\JWT\ExpiredException If the token has expired. + * @return null|object + */ + public function verifyIdToken($publicKey = null, $allowed_algs = []) + { + $idToken = $this->getIdToken(); + if (is_null($idToken)) { + return null; + } + + $resp = $this->jwtDecode($idToken, $publicKey, $allowed_algs); + if (!property_exists($resp, 'aud')) { + throw new \DomainException('No audience found the id token'); + } + if ($resp->aud != $this->getAudience()) { + throw new \DomainException('Wrong audience present in the id token'); + } + + return $resp; + } + + /** + * Obtains the encoded jwt from the instance data. + * + * @param array $config array optional configuration parameters + * @return string + */ + public function toJwt(array $config = []) + { + if (is_null($this->getSigningKey())) { + throw new \DomainException('No signing key available'); + } + if (is_null($this->getSigningAlgorithm())) { + throw new \DomainException('No signing algorithm specified'); + } + $now = time(); + + $opts = array_merge([ + 'skew' => self::DEFAULT_SKEW_SECONDS, + ], $config); + + $assertion = [ + 'iss' => $this->getIssuer(), + 'exp' => ($now + $this->getExpiry()), + 'iat' => ($now - $opts['skew']), + ]; + foreach ($assertion as $k => $v) { + if (is_null($v)) { + throw new \DomainException($k . ' should not be null'); + } + } + if (!(is_null($this->getAudience()))) { + $assertion['aud'] = $this->getAudience(); + } + + if (!(is_null($this->getScope()))) { + $assertion['scope'] = $this->getScope(); + } + + if (empty($assertion['scope']) && empty($assertion['aud'])) { + throw new \DomainException('one of scope or aud should not be null'); + } + + if (!(is_null($this->getSub()))) { + $assertion['sub'] = $this->getSub(); + } + $assertion += $this->getAdditionalClaims(); + + return JWT::encode( + $assertion, + $this->getSigningKey(), + $this->getSigningAlgorithm(), + $this->getSigningKeyId() + ); + } + + /** + * Generates a request for token credentials. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return RequestInterface the authorization Url. + */ + public function generateCredentialsRequest(callable $httpHandler = null) + { + $uri = $this->getTokenCredentialUri(); + if (is_null($uri)) { + throw new \DomainException('No token credential URI was set.'); + } + + $grantType = $this->getGrantType(); + $params = ['grant_type' => $grantType]; + switch ($grantType) { + case 'authorization_code': + $params['code'] = $this->getCode(); + $params['redirect_uri'] = $this->getRedirectUri(); + if ($this->codeVerifier) { + $params['code_verifier'] = $this->codeVerifier; + } + $this->addClientCredentials($params); + break; + case 'password': + $params['username'] = $this->getUsername(); + $params['password'] = $this->getPassword(); + $this->addClientCredentials($params); + break; + case 'refresh_token': + $params['refresh_token'] = $this->getRefreshToken(); + $this->addClientCredentials($params); + break; + case self::JWT_URN: + $params['assertion'] = $this->toJwt(); + break; + case self::STS_URN: + $token = $this->subjectTokenFetcher->fetchSubjectToken($httpHandler); + $params['subject_token'] = $token; + $params['subject_token_type'] = $this->subjectTokenType; + $params += array_filter([ + 'resource' => $this->resource, + 'audience' => $this->audience, + 'scope' => $this->getScope(), + 'requested_token_type' => self::STS_REQUESTED_TOKEN_TYPE, + 'actor_token' => $this->actorToken, + 'actor_token_type' => $this->actorTokenType, + ]); + if ($this->additionalOptions) { + $params['options'] = json_encode($this->additionalOptions); + } + break; + default: + if (!is_null($this->getRedirectUri())) { + # Grant type was supposed to be 'authorization_code', as there + # is a redirect URI. + throw new \DomainException('Missing authorization code'); + } + unset($params['grant_type']); + if (!is_null($grantType)) { + $params['grant_type'] = $grantType; + } + $params = array_merge($params, $this->getExtensionParams()); + } + + $headers = [ + 'Cache-Control' => 'no-store', + 'Content-Type' => 'application/x-www-form-urlencoded', + ]; + + return new Request( + 'POST', + $uri, + $headers, + Query::build($params) + ); + } + + /** + * Fetches the auth tokens based on the current state. + * + * @param callable $httpHandler callback which delivers psr7 request + * @return array the response + */ + public function fetchAuthToken(callable $httpHandler = null) + { + if (is_null($httpHandler)) { + $httpHandler = HttpHandlerFactory::build(HttpClientCache::getHttpClient()); + } + + $response = $httpHandler($this->generateCredentialsRequest($httpHandler)); + $credentials = $this->parseTokenResponse($response); + $this->updateToken($credentials); + if (isset($credentials['scope'])) { + $this->setGrantedScope($credentials['scope']); + } + + return $credentials; + } + + /** + * Obtains a key that can used to cache the results of #fetchAuthToken. + * + * The key is derived from the scopes. + * + * @return ?string a key that may be used to cache the auth token. + */ + public function getCacheKey() + { + if (is_array($this->scope)) { + return implode(':', $this->scope); + } + + if ($this->audience) { + return $this->audience; + } + + // If scope has not set, return null to indicate no caching. + return null; + } + + /** + * Parses the fetched tokens. + * + * @param ResponseInterface $resp the response. + * @return array the tokens parsed from the response body. + * @throws \Exception + */ + public function parseTokenResponse(ResponseInterface $resp) + { + $body = (string)$resp->getBody(); + if ($resp->hasHeader('Content-Type') && + $resp->getHeaderLine('Content-Type') == 'application/x-www-form-urlencoded' + ) { + $res = []; + parse_str($body, $res); + + return $res; + } + + // Assume it's JSON; if it's not throw an exception + if (null === $res = json_decode($body, true)) { + throw new \Exception('Invalid JSON response'); + } + + return $res; + } + + /** + * Updates an OAuth 2.0 client. + * + * Example: + * ``` + * $oauth->updateToken([ + * 'refresh_token' => 'n4E9O119d', + * 'access_token' => 'FJQbwq9', + * 'expires_in' => 3600 + * ]); + * ``` + * + * @param array $config + * The configuration parameters related to the token. + * + * - refresh_token + * The refresh token associated with the access token + * to be refreshed. + * + * - access_token + * The current access token for this client. + * + * - id_token + * The current ID token for this client. + * + * - expires_in + * The time in seconds until access token expiration. + * + * - expires_at + * The time as an integer number of seconds since the Epoch + * + * - issued_at + * The timestamp that the token was issued at. + * @return void + */ + public function updateToken(array $config) + { + $opts = array_merge([ + 'extensionParams' => [], + 'access_token' => null, + 'id_token' => null, + 'expires_in' => null, + 'expires_at' => null, + 'issued_at' => null, + 'scope' => null, + ], $config); + + $this->setExpiresAt($opts['expires_at']); + $this->setExpiresIn($opts['expires_in']); + // By default, the token is issued at `Time.now` when `expiresIn` is set, + // but this can be used to supply a more precise time. + if (!is_null($opts['issued_at'])) { + $this->setIssuedAt($opts['issued_at']); + } + + $this->setAccessToken($opts['access_token']); + $this->setIdToken($opts['id_token']); + + // The refresh token should only be updated if a value is explicitly + // passed in, as some access token responses do not include a refresh + // token. + if (array_key_exists('refresh_token', $opts)) { + $this->setRefreshToken($opts['refresh_token']); + } + + // Required for STS response. An identifier for the representation of + // the issued security token. + if (array_key_exists('issued_token_type', $opts)) { + $this->issuedTokenType = $opts['issued_token_type']; + } + } + + /** + * Builds the authorization Uri that the user should be redirected to. + * + * @param array $config configuration options that customize the return url. + * @return UriInterface the authorization Url. + * @throws InvalidArgumentException + */ + public function buildFullAuthorizationUri(array $config = []) + { + if (is_null($this->getAuthorizationUri())) { + throw new InvalidArgumentException( + 'requires an authorizationUri to have been set' + ); + } + + $params = array_merge([ + 'response_type' => 'code', + 'access_type' => 'offline', + 'client_id' => $this->clientId, + 'redirect_uri' => $this->redirectUri, + 'state' => $this->state, + 'scope' => $this->getScope(), + ], $config); + + // Validate the auth_params + if (is_null($params['client_id'])) { + throw new InvalidArgumentException( + 'missing the required client identifier' + ); + } + if (is_null($params['redirect_uri'])) { + throw new InvalidArgumentException('missing the required redirect URI'); + } + if (!empty($params['prompt']) && !empty($params['approval_prompt'])) { + throw new InvalidArgumentException( + 'prompt and approval_prompt are mutually exclusive' + ); + } + if ($this->codeVerifier) { + $params['code_challenge'] = $this->getCodeChallenge($this->codeVerifier); + $params['code_challenge_method'] = $this->getCodeChallengeMethod(); + } + + // Construct the uri object; return it if it is valid. + $result = clone $this->authorizationUri; + $existingParams = Query::parse($result->getQuery()); + + $result = $result->withQuery( + Query::build(array_merge($existingParams, $params)) + ); + + if ($result->getScheme() != 'https') { + throw new InvalidArgumentException( + 'Authorization endpoint must be protected by TLS' + ); + } + + return $result; + } + + /** + * @return string|null + */ + public function getCodeVerifier(): ?string + { + return $this->codeVerifier; + } + + /** + * A cryptographically random string that is used to correlate the + * authorization request to the token request. + * + * The code verifier for PKCE for OAuth 2.0. When set, the authorization + * URI will contain the Code Challenge and Code Challenge Method querystring + * parameters, and the token URI will contain the Code Verifier parameter. + * + * @see https://datatracker.ietf.org/doc/html/rfc7636 + * + * @param string|null $codeVerifier + */ + public function setCodeVerifier(?string $codeVerifier): void + { + $this->codeVerifier = $codeVerifier; + } + + /** + * Generates a random 128-character string for the "code_verifier" parameter + * in PKCE for OAuth 2.0. This is a cryptographically random string that is + * determined using random_int, hashed using "hash" and sha256, and base64 + * encoded. + * + * When this method is called, the code verifier is set on the object. + * + * @return string + */ + public function generateCodeVerifier(): string + { + return $this->codeVerifier = $this->generateRandomString(128); + } + + private function getCodeChallenge(string $randomString): string + { + return rtrim(strtr(base64_encode(hash('sha256', $randomString, true)), '+/', '-_'), '='); + } + + private function getCodeChallengeMethod(): string + { + return 'S256'; + } + + private function generateRandomString(int $length): string + { + $validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~'; + $validCharsLen = strlen($validChars); + $str = ''; + $i = 0; + while ($i++ < $length) { + $str .= $validChars[random_int(0, $validCharsLen - 1)]; + } + return $str; + } + + /** + * Sets the authorization server's HTTP endpoint capable of authenticating + * the end-user and obtaining authorization. + * + * @param string $uri + * @return void + */ + public function setAuthorizationUri($uri) + { + $this->authorizationUri = $this->coerceUri($uri); + } + + /** + * Gets the authorization server's HTTP endpoint capable of authenticating + * the end-user and obtaining authorization. + * + * @return ?UriInterface + */ + public function getAuthorizationUri() + { + return $this->authorizationUri; + } + + /** + * Gets the authorization server's HTTP endpoint capable of issuing tokens + * and refreshing expired tokens. + * + * @return ?UriInterface + */ + public function getTokenCredentialUri() + { + return $this->tokenCredentialUri; + } + + /** + * Sets the authorization server's HTTP endpoint capable of issuing tokens + * and refreshing expired tokens. + * + * @param string $uri + * @return void + */ + public function setTokenCredentialUri($uri) + { + $this->tokenCredentialUri = $this->coerceUri($uri); + } + + /** + * Gets the redirection URI used in the initial request. + * + * @return ?string + */ + public function getRedirectUri() + { + return $this->redirectUri; + } + + /** + * Sets the redirection URI used in the initial request. + * + * @param ?string $uri + * @return void + */ + public function setRedirectUri($uri) + { + if (is_null($uri)) { + $this->redirectUri = null; + + return; + } + // redirect URI must be absolute + if (!$this->isAbsoluteUri($uri)) { + // "postmessage" is a reserved URI string in Google-land + // @see https://developers.google.com/identity/sign-in/web/server-side-flow + if ('postmessage' !== (string)$uri) { + throw new InvalidArgumentException( + 'Redirect URI must be absolute' + ); + } + } + $this->redirectUri = (string)$uri; + } + + /** + * Gets the scope of the access requests as a space-delimited String. + * + * @return ?string + */ + public function getScope() + { + if (is_null($this->scope)) { + return $this->scope; + } + + return implode(' ', $this->scope); + } + + /** + * Sets the scope of the access request, expressed either as an Array or as + * a space-delimited String. + * + * @param string|array|null $scope + * @return void + * @throws InvalidArgumentException + */ + public function setScope($scope) + { + if (is_null($scope)) { + $this->scope = null; + } elseif (is_string($scope)) { + $this->scope = explode(' ', $scope); + } elseif (is_array($scope)) { + foreach ($scope as $s) { + $pos = strpos($s, ' '); + if ($pos !== false) { + throw new InvalidArgumentException( + 'array scope values should not contain spaces' + ); + } + } + $this->scope = $scope; + } else { + throw new InvalidArgumentException( + 'scopes should be a string or array of strings' + ); + } + } + + /** + * Gets the current grant type. + * + * @return ?string + */ + public function getGrantType() + { + if (!is_null($this->grantType)) { + return $this->grantType; + } + + // Returns the inferred grant type, based on the current object instance + // state. + if (!is_null($this->code)) { + return 'authorization_code'; + } + + if (!is_null($this->refreshToken)) { + return 'refresh_token'; + } + + if (!is_null($this->username) && !is_null($this->password)) { + return 'password'; + } + + if (!is_null($this->issuer) && !is_null($this->signingKey)) { + return self::JWT_URN; + } + + if (!is_null($this->subjectTokenFetcher) && !is_null($this->subjectTokenType)) { + return self::STS_URN; + } + + return null; + } + + /** + * Sets the current grant type. + * + * @param string $grantType + * @return void + * @throws InvalidArgumentException + */ + public function setGrantType($grantType) + { + if (in_array($grantType, self::$knownGrantTypes)) { + $this->grantType = $grantType; + } else { + // validate URI + if (!$this->isAbsoluteUri($grantType)) { + throw new InvalidArgumentException( + 'invalid grant type' + ); + } + $this->grantType = (string)$grantType; + } + } + + /** + * Gets an arbitrary string designed to allow the client to maintain state. + * + * @return string + */ + public function getState() + { + return $this->state; + } + + /** + * Sets an arbitrary string designed to allow the client to maintain state. + * + * @param string $state + * @return void + */ + public function setState($state) + { + $this->state = $state; + } + + /** + * Gets the authorization code issued to this client. + * + * @return string + */ + public function getCode() + { + return $this->code; + } + + /** + * Sets the authorization code issued to this client. + * + * @param string $code + * @return void + */ + public function setCode($code) + { + $this->code = $code; + } + + /** + * Gets the resource owner's username. + * + * @return string + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the resource owner's username. + * + * @param string $username + * @return void + */ + public function setUsername($username) + { + $this->username = $username; + } + + /** + * Gets the resource owner's password. + * + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the resource owner's password. + * + * @param string $password + * @return void + */ + public function setPassword($password) + { + $this->password = $password; + } + + /** + * Sets a unique identifier issued to the client to identify itself to the + * authorization server. + * + * @return string + */ + public function getClientId() + { + return $this->clientId; + } + + /** + * Sets a unique identifier issued to the client to identify itself to the + * authorization server. + * + * @param string $clientId + * @return void + */ + public function setClientId($clientId) + { + $this->clientId = $clientId; + } + + /** + * Gets a shared symmetric secret issued by the authorization server, which + * is used to authenticate the client. + * + * @return string + */ + public function getClientSecret() + { + return $this->clientSecret; + } + + /** + * Sets a shared symmetric secret issued by the authorization server, which + * is used to authenticate the client. + * + * @param string $clientSecret + * @return void + */ + public function setClientSecret($clientSecret) + { + $this->clientSecret = $clientSecret; + } + + /** + * Gets the Issuer ID when using assertion profile. + * + * @return ?string + */ + public function getIssuer() + { + return $this->issuer; + } + + /** + * Sets the Issuer ID when using assertion profile. + * + * @param string $issuer + * @return void + */ + public function setIssuer($issuer) + { + $this->issuer = $issuer; + } + + /** + * Gets the target sub when issuing assertions. + * + * @return ?string + */ + public function getSub() + { + return $this->sub; + } + + /** + * Sets the target sub when issuing assertions. + * + * @param string $sub + * @return void + */ + public function setSub($sub) + { + $this->sub = $sub; + } + + /** + * Gets the target audience when issuing assertions. + * + * @return ?string + */ + public function getAudience() + { + return $this->audience; + } + + /** + * Sets the target audience when issuing assertions. + * + * @param string $audience + * @return void + */ + public function setAudience($audience) + { + $this->audience = $audience; + } + + /** + * Gets the signing key when using an assertion profile. + * + * @return ?string + */ + public function getSigningKey() + { + return $this->signingKey; + } + + /** + * Sets the signing key when using an assertion profile. + * + * @param string $signingKey + * @return void + */ + public function setSigningKey($signingKey) + { + $this->signingKey = $signingKey; + } + + /** + * Gets the signing key id when using an assertion profile. + * + * @return ?string + */ + public function getSigningKeyId() + { + return $this->signingKeyId; + } + + /** + * Sets the signing key id when using an assertion profile. + * + * @param string $signingKeyId + * @return void + */ + public function setSigningKeyId($signingKeyId) + { + $this->signingKeyId = $signingKeyId; + } + + /** + * Gets the signing algorithm when using an assertion profile. + * + * @return ?string + */ + public function getSigningAlgorithm() + { + return $this->signingAlgorithm; + } + + /** + * Sets the signing algorithm when using an assertion profile. + * + * @param ?string $signingAlgorithm + * @return void + */ + public function setSigningAlgorithm($signingAlgorithm) + { + if (is_null($signingAlgorithm)) { + $this->signingAlgorithm = null; + } elseif (!in_array($signingAlgorithm, self::$knownSigningAlgorithms)) { + throw new InvalidArgumentException('unknown signing algorithm'); + } else { + $this->signingAlgorithm = $signingAlgorithm; + } + } + + /** + * Gets the set of parameters used by extension when using an extension + * grant type. + * + * @return array + */ + public function getExtensionParams() + { + return $this->extensionParams; + } + + /** + * Sets the set of parameters used by extension when using an extension + * grant type. + * + * @param array $extensionParams + * @return void + */ + public function setExtensionParams($extensionParams) + { + $this->extensionParams = $extensionParams; + } + + /** + * Gets the number of seconds assertions are valid for. + * + * @return int + */ + public function getExpiry() + { + return $this->expiry; + } + + /** + * Sets the number of seconds assertions are valid for. + * + * @param int $expiry + * @return void + */ + public function setExpiry($expiry) + { + $this->expiry = $expiry; + } + + /** + * Gets the lifetime of the access token in seconds. + * + * @return int + */ + public function getExpiresIn() + { + return $this->expiresIn; + } + + /** + * Sets the lifetime of the access token in seconds. + * + * @param ?int $expiresIn + * @return void + */ + public function setExpiresIn($expiresIn) + { + if (is_null($expiresIn)) { + $this->expiresIn = null; + $this->issuedAt = null; + } else { + $this->issuedAt = time(); + $this->expiresIn = (int)$expiresIn; + } + } + + /** + * Gets the time the current access token expires at. + * + * @return ?int + */ + public function getExpiresAt() + { + if (!is_null($this->expiresAt)) { + return $this->expiresAt; + } + + if (!is_null($this->issuedAt) && !is_null($this->expiresIn)) { + return $this->issuedAt + $this->expiresIn; + } + + return null; + } + + /** + * Returns true if the acccess token has expired. + * + * @return bool + */ + public function isExpired() + { + $expiration = $this->getExpiresAt(); + $now = time(); + + return !is_null($expiration) && $now >= $expiration; + } + + /** + * Sets the time the current access token expires at. + * + * @param int $expiresAt + * @return void + */ + public function setExpiresAt($expiresAt) + { + $this->expiresAt = $expiresAt; + } + + /** + * Gets the time the current access token was issued at. + * + * @return ?int + */ + public function getIssuedAt() + { + return $this->issuedAt; + } + + /** + * Sets the time the current access token was issued at. + * + * @param int $issuedAt + * @return void + */ + public function setIssuedAt($issuedAt) + { + $this->issuedAt = $issuedAt; + } + + /** + * Gets the current access token. + * + * @return ?string + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the current access token. + * + * @param string $accessToken + * @return void + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + } + + /** + * Gets the current ID token. + * + * @return ?string + */ + public function getIdToken() + { + return $this->idToken; + } + + /** + * Sets the current ID token. + * + * @param string $idToken + * @return void + */ + public function setIdToken($idToken) + { + $this->idToken = $idToken; + } + + /** + * Get the granted space-separated scopes (if they exist) for the last + * fetched token. + * + * @return string|null + */ + public function getGrantedScope() + { + return $this->grantedScope; + } + + /** + * Sets the current ID token. + * + * @param string $grantedScope + * @return void + */ + public function setGrantedScope($grantedScope) + { + $this->grantedScope = $grantedScope; + } + + /** + * Gets the refresh token associated with the current access token. + * + * @return ?string + */ + public function getRefreshToken() + { + return $this->refreshToken; + } + + /** + * Sets the refresh token associated with the current access token. + * + * @param string $refreshToken + * @return void + */ + public function setRefreshToken($refreshToken) + { + $this->refreshToken = $refreshToken; + } + + /** + * Sets additional claims to be included in the JWT token + * + * @param array $additionalClaims + * @return void + */ + public function setAdditionalClaims(array $additionalClaims) + { + $this->additionalClaims = $additionalClaims; + } + + /** + * Gets the additional claims to be included in the JWT token. + * + * @return array + */ + public function getAdditionalClaims() + { + return $this->additionalClaims; + } + + /** + * Gets the additional claims to be included in the JWT token. + * + * @return ?string + */ + public function getIssuedTokenType() + { + return $this->issuedTokenType; + } + + /** + * The expiration of the last received token. + * + * @return array|null + */ + public function getLastReceivedToken() + { + if ($token = $this->getAccessToken()) { + // the bare necessity of an auth token + $authToken = [ + 'access_token' => $token, + 'expires_at' => $this->getExpiresAt(), + ]; + } elseif ($idToken = $this->getIdToken()) { + $authToken = [ + 'id_token' => $idToken, + 'expires_at' => $this->getExpiresAt(), + ]; + } else { + return null; + } + + if ($expiresIn = $this->getExpiresIn()) { + $authToken['expires_in'] = $expiresIn; + } + if ($issuedAt = $this->getIssuedAt()) { + $authToken['issued_at'] = $issuedAt; + } + if ($refreshToken = $this->getRefreshToken()) { + $authToken['refresh_token'] = $refreshToken; + } + + return $authToken; + } + + /** + * Get the client ID. + * + * Alias of {@see Google\Auth\OAuth2::getClientId()}. + * + * @param callable $httpHandler + * @return string + * @access private + */ + public function getClientName(callable $httpHandler = null) + { + return $this->getClientId(); + } + + /** + * @todo handle uri as array + * + * @param ?string $uri + * @return null|UriInterface + */ + private function coerceUri($uri) + { + if (is_null($uri)) { + return null; + } + + return Utils::uriFor($uri); + } + + /** + * @param string $idToken + * @param Key|Key[]|string|string[] $publicKey + * @param string|string[] $allowedAlgs + * @return object + */ + private function jwtDecode($idToken, $publicKey, $allowedAlgs) + { + $keys = $this->getFirebaseJwtKeys($publicKey, $allowedAlgs); + + // Default exception if none are caught. We are using the same exception + // class and message from firebase/php-jwt to preserve backwards + // compatibility. + $e = new \InvalidArgumentException('Key may not be empty'); + foreach ($keys as $key) { + try { + return JWT::decode($idToken, $key); + } catch (\Exception $e) { + // try next alg + } + } + throw $e; + } + + /** + * @param Key|Key[]|string|string[] $publicKey + * @param string|string[] $allowedAlgs + * @return Key[] + */ + private function getFirebaseJwtKeys($publicKey, $allowedAlgs) + { + // If $publicKey is instance of Key, return it + if ($publicKey instanceof Key) { + return [$publicKey]; + } + + // If $allowedAlgs is empty, $publicKey must be Key or Key[]. + if (empty($allowedAlgs)) { + $keys = []; + foreach ((array) $publicKey as $kid => $pubKey) { + if (!$pubKey instanceof Key) { + throw new \InvalidArgumentException(sprintf( + 'When allowed algorithms is empty, the public key must' + . 'be an instance of %s or an array of %s objects', + Key::class, + Key::class + )); + } + $keys[$kid] = $pubKey; + } + return $keys; + } + + $allowedAlg = null; + if (is_string($allowedAlgs)) { + $allowedAlg = $allowedAlgs; + } elseif (is_array($allowedAlgs)) { + if (count($allowedAlgs) > 1) { + throw new \InvalidArgumentException( + 'To have multiple allowed algorithms, You must provide an' + . ' array of Firebase\JWT\Key objects.' + . ' See https://github.com/firebase/php-jwt for more information.'); + } + $allowedAlg = array_pop($allowedAlgs); + } else { + throw new \InvalidArgumentException('allowed algorithms must be a string or array.'); + } + + if (is_array($publicKey)) { + // When publicKey is greater than 1, create keys with the single alg. + $keys = []; + foreach ($publicKey as $kid => $pubKey) { + if ($pubKey instanceof Key) { + $keys[$kid] = $pubKey; + } else { + $keys[$kid] = new Key($pubKey, $allowedAlg); + } + } + return $keys; + } + + return [new Key($publicKey, $allowedAlg)]; + } + + /** + * Determines if the URI is absolute based on its scheme and host or path + * (RFC 3986). + * + * @param string $uri + * @return bool + */ + private function isAbsoluteUri($uri) + { + $uri = $this->coerceUri($uri); + + return $uri->getScheme() && ($uri->getHost() || $uri->getPath()); + } + + /** + * @param array $params + * @return array + */ + private function addClientCredentials(&$params) + { + $clientId = $this->getClientId(); + $clientSecret = $this->getClientSecret(); + + if ($clientId && $clientSecret) { + $params['client_id'] = $clientId; + $params['client_secret'] = $clientSecret; + } + + return $params; + } +} diff --git a/vendor/google/auth/src/ProjectIdProviderInterface.php b/vendor/google/auth/src/ProjectIdProviderInterface.php new file mode 100644 index 0000000..0a41f78 --- /dev/null +++ b/vendor/google/auth/src/ProjectIdProviderInterface.php @@ -0,0 +1,32 @@ +auth->getSigningKey(); + + $signedString = ''; + if (class_exists(phpseclib3\Crypt\RSA::class) && !$forceOpenssl) { + $key = PublicKeyLoader::load($privateKey); + $rsa = $key->withHash('sha256')->withPadding(RSA::SIGNATURE_PKCS1); + + $signedString = $rsa->sign($stringToSign); + } elseif (extension_loaded('openssl')) { + openssl_sign($stringToSign, $signedString, $privateKey, 'sha256WithRSAEncryption'); + } else { + // @codeCoverageIgnoreStart + throw new \RuntimeException('OpenSSL is not installed.'); + } + // @codeCoverageIgnoreEnd + + return base64_encode($signedString); + } +} diff --git a/vendor/google/auth/src/SignBlobInterface.php b/vendor/google/auth/src/SignBlobInterface.php new file mode 100644 index 0000000..5f2c944 --- /dev/null +++ b/vendor/google/auth/src/SignBlobInterface.php @@ -0,0 +1,44 @@ + $metadata metadata hashmap + * @param string $authUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * @return array updated metadata hashmap + */ + public function updateMetadata( + $metadata, + $authUri = null, + callable $httpHandler = null + ); +} diff --git a/vendor/google/auth/src/UpdateMetadataTrait.php b/vendor/google/auth/src/UpdateMetadataTrait.php new file mode 100644 index 0000000..fd33e0d --- /dev/null +++ b/vendor/google/auth/src/UpdateMetadataTrait.php @@ -0,0 +1,66 @@ + $metadata metadata hashmap + * @param string $authUri optional auth uri + * @param callable $httpHandler callback which delivers psr7 request + * @return array updated metadata hashmap + */ + public function updateMetadata( + $metadata, + $authUri = null, + callable $httpHandler = null + ) { + if (isset($metadata[self::AUTH_METADATA_KEY])) { + // Auth metadata has already been set + return $metadata; + } + $result = $this->fetchAuthToken($httpHandler); + $metadata_copy = $metadata; + if (isset($result['access_token'])) { + $metadata_copy[self::AUTH_METADATA_KEY] = ['Bearer ' . $result['access_token']]; + } elseif (isset($result['id_token'])) { + $metadata_copy[self::AUTH_METADATA_KEY] = ['Bearer ' . $result['id_token']]; + } + return $metadata_copy; + } +} diff --git a/vendor/guzzlehttp/guzzle/CHANGELOG.md b/vendor/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 0000000..13709d1 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,1633 @@ +# Change Log + +Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. + + +## 7.8.1 - 2023-12-03 + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + + +## 7.8.0 - 2023-08-27 + +### Added + +- Support for PHP 8.3 +- Added automatic closing of handles on `CurlFactory` object destruction + + +## 7.7.1 - 2023-08-27 + +### Changed + +- Remove the need for `AllowDynamicProperties` in `CurlMultiHandler` + + +## 7.7.0 - 2023-05-21 + +### Added + +- Support `guzzlehttp/promises` v2 + + +## 7.6.1 - 2023-05-15 + +### Fixed + +- Fix `SetCookie::fromString` MaxAge deprecation warning and skip invalid MaxAge values + + +## 7.6.0 - 2023-05-14 + +### Added + +- Support for setting the minimum TLS version in a unified way +- Apply on request the version set in options parameters + + +## 7.5.2 - 2023-05-14 + +### Fixed + +- Fixed set cookie constructor validation +- Fixed handling of files with `'0'` body + +### Changed + +- Corrected docs and default connect timeout value to 300 seconds + + +## 7.5.1 - 2023-04-17 + +### Fixed + +- Fixed `NO_PROXY` settings so that setting the `proxy` option to `no` overrides the env variable + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^1.9.1 || ^2.4.5` + + +## 7.5.0 - 2022-08-28 + +### Added + +- Support PHP 8.2 +- Add request to delay closure params + + +## 7.4.5 - 2022-06-20 + +### Fixed + +* Fix change in port should be considered a change in origin +* Fix `CURLOPT_HTTPAUTH` option not cleared on change of origin + + +## 7.4.4 - 2022-06-09 + +### Fixed + +* Fix failure to strip Authorization header on HTTP downgrade +* Fix failure to strip the Cookie header on change in host or HTTP downgrade + + +## 7.4.3 - 2022-05-25 + +### Fixed + +* Fix cross-domain cookie leakage + + +## 7.4.2 - 2022-03-20 + +### Fixed + +- Remove curl auth on cross-domain redirects to align with the Authorization HTTP header +- Reject non-HTTP schemes in StreamHandler +- Set a default ssl.peer_name context in StreamHandler to allow `force_ip_resolve` + + +## 7.4.1 - 2021-12-06 + +### Changed + +- Replaced implicit URI to string coercion [#2946](https://github.com/guzzle/guzzle/pull/2946) +- Allow `symfony/deprecation-contracts` version 3 [#2961](https://github.com/guzzle/guzzle/pull/2961) + +### Fixed + +- Only close curl handle if it's done [#2950](https://github.com/guzzle/guzzle/pull/2950) + + +## 7.4.0 - 2021-10-18 + +### Added + +- Support PHP 8.1 [#2929](https://github.com/guzzle/guzzle/pull/2929), [#2939](https://github.com/guzzle/guzzle/pull/2939) +- Support `psr/log` version 2 and 3 [#2943](https://github.com/guzzle/guzzle/pull/2943) + +### Fixed + +- Make sure we always call `restore_error_handler()` [#2915](https://github.com/guzzle/guzzle/pull/2915) +- Fix progress parameter type compatibility between the cURL and stream handlers [#2936](https://github.com/guzzle/guzzle/pull/2936) +- Throw `InvalidArgumentException` when an incorrect `headers` array is provided [#2916](https://github.com/guzzle/guzzle/pull/2916), [#2942](https://github.com/guzzle/guzzle/pull/2942) + +### Changed + +- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945) + + +## 7.3.0 - 2021-03-23 + +### Added + +- Support for DER and P12 certificates [#2413](https://github.com/guzzle/guzzle/pull/2413) +- Support the cURL (http://) scheme for StreamHandler proxies [#2850](https://github.com/guzzle/guzzle/pull/2850) +- Support for `guzzlehttp/psr7:^2.0` [#2878](https://github.com/guzzle/guzzle/pull/2878) + +### Fixed + +- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872) + + +## 7.2.0 - 2020-10-10 + +### Added + +- Support for PHP 8 [#2712](https://github.com/guzzle/guzzle/pull/2712), [#2715](https://github.com/guzzle/guzzle/pull/2715), [#2789](https://github.com/guzzle/guzzle/pull/2789) +- Support passing a body summarizer to the http errors middleware [#2795](https://github.com/guzzle/guzzle/pull/2795) + +### Fixed + +- Handle exceptions during response creation [#2591](https://github.com/guzzle/guzzle/pull/2591) +- Fix CURLOPT_ENCODING not to be overwritten [#2595](https://github.com/guzzle/guzzle/pull/2595) +- Make sure the Request always has a body object [#2804](https://github.com/guzzle/guzzle/pull/2804) + +### Changed + +- The `TooManyRedirectsException` has a response [#2660](https://github.com/guzzle/guzzle/pull/2660) +- Avoid "functions" from dependencies [#2712](https://github.com/guzzle/guzzle/pull/2712) + +### Deprecated + +- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786) + + +## 7.1.1 - 2020-09-30 + +### Fixed + +- Incorrect EOF detection for response body streams on Windows. + +### Changed + +- We dont connect curl `sink` on HEAD requests. +- Removed some PHP 5 workarounds + + +## 7.1.0 - 2020-09-22 + +### Added + +- `GuzzleHttp\MessageFormatterInterface` + +### Fixed + +- Fixed issue that caused cookies with no value not to be stored. +- On redirects, we allow all safe methods like GET, HEAD and OPTIONS. +- Fixed logging on empty responses. +- Make sure MessageFormatter::format returns string + +### Deprecated + +- All functions in `GuzzleHttp` has been deprecated. Use static methods on `Utils` instead. +- `ClientInterface::getConfig()` +- `Client::getConfig()` +- `Client::__call()` +- `Utils::defaultCaBundle()` +- `CurlFactory::LOW_CURL_VERSION_NUMBER` + + +## 7.0.1 - 2020-06-27 + +* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699) + + +## 7.0.0 - 2020-06-27 + +No changes since 7.0.0-rc1. + + +## 7.0.0-rc1 - 2020-06-15 + +### Changed + +* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629) +* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675) + + +## 7.0.0-beta2 - 2020-05-25 + +### Added + +* Using `Utils` class instead of functions in the `GuzzleHttp` namespace. [#2546](https://github.com/guzzle/guzzle/pull/2546) +* `ClientInterface::MAJOR_VERSION` [#2583](https://github.com/guzzle/guzzle/pull/2583) + +### Changed + +* Avoid the `getenv` function when unsafe [#2531](https://github.com/guzzle/guzzle/pull/2531) +* Added real client methods [#2529](https://github.com/guzzle/guzzle/pull/2529) +* Avoid functions due to global install conflicts [#2546](https://github.com/guzzle/guzzle/pull/2546) +* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) +* Adding methods for HTTP verbs like `Client::get()`, `Client::head()`, `Client::patch()` etc [#2529](https://github.com/guzzle/guzzle/pull/2529) +* `ConnectException` extends `TransferException` [#2541](https://github.com/guzzle/guzzle/pull/2541) +* Updated the default User Agent to "GuzzleHttp/7" [#2654](https://github.com/guzzle/guzzle/pull/2654) + +### Fixed + +* Various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) + +### Removed + +* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528) + + +## 7.0.0-beta1 - 2019-12-30 + +The diff might look very big but 95% of Guzzle users will be able to upgrade without modification. +Please see [the upgrade document](UPGRADING.md) that describes all BC breaking changes. + +### Added + +* Implement PSR-18 and dropped PHP 5 support [#2421](https://github.com/guzzle/guzzle/pull/2421) [#2474](https://github.com/guzzle/guzzle/pull/2474) +* PHP 7 types [#2442](https://github.com/guzzle/guzzle/pull/2442) [#2449](https://github.com/guzzle/guzzle/pull/2449) [#2466](https://github.com/guzzle/guzzle/pull/2466) [#2497](https://github.com/guzzle/guzzle/pull/2497) [#2499](https://github.com/guzzle/guzzle/pull/2499) +* IDN support for redirects [2424](https://github.com/guzzle/guzzle/pull/2424) + +### Changed + +* Dont allow passing null as third argument to `BadResponseException::__construct()` [#2427](https://github.com/guzzle/guzzle/pull/2427) +* Use SAPI constant instead of method call [#2450](https://github.com/guzzle/guzzle/pull/2450) +* Use native function invocation [#2444](https://github.com/guzzle/guzzle/pull/2444) +* Better defaults for PHP installations with old ICU lib [2454](https://github.com/guzzle/guzzle/pull/2454) +* Added visibility to all constants [#2462](https://github.com/guzzle/guzzle/pull/2462) +* Dont allow passing `null` as URI to `Client::request()` and `Client::requestAsync()` [#2461](https://github.com/guzzle/guzzle/pull/2461) +* Widen the exception argument to throwable [#2495](https://github.com/guzzle/guzzle/pull/2495) + +### Fixed + +* Logging when Promise rejected with a string [#2311](https://github.com/guzzle/guzzle/pull/2311) + +### Removed + +* Class `SeekException` [#2162](https://github.com/guzzle/guzzle/pull/2162) +* `RequestException::getResponseBodySummary()` [#2425](https://github.com/guzzle/guzzle/pull/2425) +* `CookieJar::getCookieValue()` [#2433](https://github.com/guzzle/guzzle/pull/2433) +* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440) +* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464) + + +## 6.5.2 - 2019-12-23 + +* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) + + +## 6.5.1 - 2019-12-21 + +* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) +* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) + + +## 6.5.0 - 2019-12-07 + +* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) +* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) +* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) +* Deprecated `ClientInterface::VERSION` + + +## 6.4.1 - 2019-10-23 + +* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that +* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` + + +## 6.4.0 - 2019-10-23 + +* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) +* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) +* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) +* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) +* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) +* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) +* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) +* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) +* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) + + +## 6.3.3 - 2018-04-22 + +* Fix: Default headers when decode_content is specified + + +## 6.3.2 - 2018-03-26 + +* Fix: Release process + + +## 6.3.1 - 2018-03-26 + +* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) +* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) +* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) +* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) +* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) +* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) +* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See + https://datatracker.ietf.org/doc/html/rfc3986#appendix-A + + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://datatracker.ietf.org/doc/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/vendor/guzzlehttp/guzzle/LICENSE b/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 0000000..fd2375d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +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/vendor/guzzlehttp/guzzle/README.md b/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 0000000..6d78a93 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,94 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP client + +[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) +[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI) +[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' +echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); + +$promise->wait(); +``` + +## Help and docs + +We use GitHub issues only to discuss bugs and new features. For support please refer to: + +- [Documentation](https://docs.guzzlephp.org) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle) +- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 | +| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 | +| 6.x | Security fixes only | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 | +| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.4 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5 +[guzzle-7-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: https://guzzle3.readthedocs.io/ +[guzzle-5-docs]: https://docs.guzzlephp.org/en/5.3/ +[guzzle-6-docs]: https://docs.guzzlephp.org/en/6.5/ +[guzzle-7-docs]: https://docs.guzzlephp.org/en/latest/ + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/guzzle/UPGRADING.md b/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 0000000..4efbb59 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1253 @@ +Guzzle Upgrade Guide +==================== + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other backwards compatibility breaking changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exceptions` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native functions calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..master). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](https://docs.guzzlephp.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](https://docs.guzzlephp.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](https://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: https://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- https://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- https://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/vendor/guzzlehttp/guzzle/composer.json b/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 0000000..69583d7 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,103 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^1.5.3 || ^2.0.1", + "guzzlehttp/psr7": "^1.9.1 || ^2.5.1", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.8.2", + "php-http/client-integration-tests": "dev-master#2c025848417c1135031fdf9c728ee53d0a7ceaee as 3.0.999", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.36 || ^9.6.15", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/BodySummarizer.php b/vendor/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 0000000..6eca94e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,28 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + return $this->truncateAt === null + ? \GuzzleHttp\Psr7\Message::bodySummary($message) + : \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 0000000..3e02e03 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,13 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. + * If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']); + } + + $this->configureDefaults($config); + } + + /** + * @param string $method + * @param array $args + * + * @return PromiseInterface|ResponseInterface + * + * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0. + */ + public function __call($method, $args) + { + if (\count($args) < 1) { + throw new InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = $args[1] ?? []; + + return \substr($method, -5) === 'Async' + ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specify this method. + * + * {@inheritDoc} + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + */ + public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = $options['headers'] ?? []; + $body = $options['body'] ?? null; + $version = $options['version'] ?? '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options); + if (\is_array($body)) { + throw $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by + * the concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return mixed + * + * @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0. + */ + public function getConfig(string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private function buildUri(UriInterface $uri, array $config): UriInterface + { + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri); + } + + if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { + $idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults(array $config): void + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Utils::getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = Utils::getenv('NO_PROXY')) { + $cleanedNoProxy = \str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (\array_keys($this->config['headers']) as $name) { + if (\strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults(array $options): array + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See \GuzzleHttp\RequestOptions. + */ + private function transfer(RequestInterface $request, array $options): PromiseInterface + { + $request = $this->applyOptions($request, $options); + /** @var HandlerStack $handler */ + $handler = $options['handler']; + + try { + return P\Create::promiseFor($handler($request, $options)); + } catch (\Exception $e) { + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions(RequestInterface $request, array &$options): RequestInterface + { + $modify = [ + 'set_headers' => [], + ]; + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + .'form_params and multipart at the same time. Use the ' + .'form_params option if you want to send application/' + .'x-www-form-urlencoded requests, and the multipart ' + .'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = Utils::jsonEncode($options['json']); + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = Psr7\Utils::streamFor($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && \is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + // Ensure that we don't have the header in different case and set the new value. + $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); + $modify['set_headers']['Authorization'] = 'Basic ' + .\base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (\is_bool($options['sink'])) { + throw new InvalidArgumentException('sink must not be a boolean'); + } + } + + if (isset($options['version'])) { + $modify['version'] = $options['version']; + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + .$request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + .'option as an array to send a request is not supported. ' + .'Please use the "form_params" request option to send a ' + .'application/x-www-form-urlencoded request, or the "multipart" ' + .'request option to send a multipart/form-data request.'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 0000000..1788e16 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function head($uri, array $options = []): ResponseInterface + { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function put($uri, array $options = []): ResponseInterface + { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function post($uri, array $options = []): ResponseInterface + { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch($uri, array $options = []): ResponseInterface + { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete($uri, array $options = []): ResponseInterface + { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function getAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function headAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function putAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function postAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function patchAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function deleteAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 0000000..c29b4b7 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,307 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray(array $cookies, string $domain): self + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true, + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + + return null; + } + + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + public function clear(string $domain = null, string $path = null, string $name = null): void + { + if (!$domain) { + $this->cookies = []; + + return; + } elseif (!$path) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name + && $cookie->matchesPath($path) + && $cookie->matchesDomain($domain)); + } + ); + } + } + + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + public function setCookie(SetCookie $cookie): bool + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: '.$result); + } + $this->removeCookieIfEmpty($cookie); + + return false; + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() + || $c->getDomain() != $cookie->getDomain() + || $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies(RequestInterface $request, ResponseInterface $response): void + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + if (!$sc->matchesDomain($request->getUri()->getHost())) { + continue; + } + // Note: At this point `$sc->getDomain()` being a public suffix should + // be rejected, but we don't want to pull in the full PSL dependency. + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request): RequestInterface + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) + && $cookie->matchesDomain($host) + && !$cookie->isExpired() + && (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName().'=' + .$cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', \implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 0000000..8c55cc6 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,80 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(string $domain = null, string $path = null, string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 0000000..290236d --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,101 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the file cannot be found or created + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = Utils::jsonEncode($json); + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } + if ($json === '') { + return; + } + + $data = Utils::jsonDecode($json, true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\is_scalar($data) && !empty($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 0000000..cb3e67c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,77 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = \json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = \json_decode($_SESSION[$this->sessionKey], true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\strlen($data)) { + throw new \RuntimeException('Invalid cookie data'); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 0000000..c9806da --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,488 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false, + ]; + + /** + * @var array Cookie data + */ + private $data; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString(string $cookie): self + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::$defaults) as $search) { + if (!\strcasecmp($search, $key)) { + if ($search === 'Max-Age') { + if (is_numeric($value)) { + $data[$search] = (int) $value; + } + } else { + $data[$search] = $value; + } + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + $this->data = self::$defaults; + + if (isset($data['Name'])) { + $this->setName($data['Name']); + } + + if (isset($data['Value'])) { + $this->setValue($data['Value']); + } + + if (isset($data['Domain'])) { + $this->setDomain($data['Domain']); + } + + if (isset($data['Path'])) { + $this->setPath($data['Path']); + } + + if (isset($data['Max-Age'])) { + $this->setMaxAge($data['Max-Age']); + } + + if (isset($data['Expires'])) { + $this->setExpires($data['Expires']); + } + + if (isset($data['Secure'])) { + $this->setSecure($data['Secure']); + } + + if (isset($data['Discard'])) { + $this->setDiscard($data['Discard']); + } + + if (isset($data['HttpOnly'])) { + $this->setHttpOnly($data['HttpOnly']); + } + + // Set the remaining values that don't have extra validation logic + foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) { + $this->data[$key] = $data[$key]; + } + + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(\time() + $this->getMaxAge()); + } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) { + $this->setExpires($expires); + } + } + + public function __toString() + { + $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}").'; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + return $this->data; + } + + /** + * Get the cookie name. + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName($name): void + { + if (!is_string($name)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Name'] = (string) $name; + } + + /** + * Get the cookie value. + * + * @return string|null + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue($value): void + { + if (!is_string($value)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Value'] = (string) $value; + } + + /** + * Get the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain + */ + public function setDomain($domain): void + { + if (!is_string($domain) && null !== $domain) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Domain'] = null === $domain ? null : (string) $domain; + } + + /** + * Get the path. + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath($path): void + { + if (!is_string($path)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Path'] = (string) $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + * + * @return int|null + */ + public function getMaxAge() + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge): void + { + if (!is_int($maxAge) && null !== $maxAge) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + * + * @return string|int|null + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp)); + } + + /** + * Get whether or not this is a secure cookie. + * + * @return bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure): void + { + if (!is_bool($secure)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Secure'] = (bool) $secure; + } + + /** + * Get whether or not this is a session cookie. + * + * @return bool|null + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard): void + { + if (!is_bool($discard)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Discard'] = (bool) $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly): void + { + if (!is_bool($httpOnly)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['HttpOnly'] = (bool) $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain) { + return true; + } + + // Remove the leading '.' as per spec in RFC 6265. + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3 + $cookieDomain = \ltrim(\strtolower($cookieDomain), '.'); + + $domain = \strtolower($domain); + + // Domain not set or exact match. + if ('' === $cookieDomain || $domain === $cookieDomain) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3 + if (\filter_var($domain, \FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name + )) { + return 'Cookie name must not contain invalid characters: ASCII ' + .'Control characters (0-31;127), space, tab and the ' + .'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0. "0" is not a valid internet + // domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === null || $domain === '') { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 0000000..a80956c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,39 @@ +request = $request; + $this->handlerContext = $handlerContext; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php b/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php new file mode 100644 index 0000000..fa3ed69 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php @@ -0,0 +1,9 @@ +getStatusCode() : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + */ + public static function wrapException(RequestInterface $request, \Throwable $e): RequestException + { + return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request sent + * @param ResponseInterface $response Response received + * @param \Throwable|null $previous Previous exception + * @param array $handlerContext Optional handler context + * @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Throwable $previous = null, + array $handlerContext = [], + BodySummarizerInterface $bodySummarizer = null + ): self { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $handlerContext + ); + } + + $level = (int) \floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri->__toString(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $handlerContext); + } + + /** + * Obfuscates URI if there is a username and a password present + */ + private static function obfuscateUri(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get the associated response + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Check if a response was received + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 0000000..8055e06 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,10 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options): EasyHandle + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle(); + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy): void + { + $resource = $easy->handle; + unset($easy->handle); + + if (\count($this->handles) >= $this->maxHandles) { + \curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); + \curl_setopt($resource, \CURLOPT_READFUNCTION, null); + \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); + \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); + \curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + */ + public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy): void + { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + ($easy->options['on_stats'])($stats); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), + ] + \curl_getinfo($easy->handle); + $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface + { + static $connectionErrors = [ + \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_COULDNT_RESOLVE_HOST => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, + ]; + + if ($easy->createResponseException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + $easy->response, + $easy->createResponseException, + $ctx + ) + ); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + $uriString = (string) $easy->request->getUri(); + if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { + $message .= \sprintf(' for %s', $uriString); + } + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return P\Create::rejectionFor($error); + } + + /** + * @return array + */ + private function getDefaultConf(EasyHandle $easy): array + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT => 300, + ]; + + if (\defined('CURLOPT_PROTOCOLS')) { + $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf): void + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf): void + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[\CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf): void + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $value = (string) $value; + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (!\strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf): void + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) + || ( + \is_link($options['verify']) === true + && ($verifyLink = \readlink($options['verify'])) !== false + && \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any acceptable encodings we need + // to overwrite this implicit header with an empty one. + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (!isset($options['sink'])) { + // Use a default temp stream if no sink was set. + $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if (!\is_string($sink)) { + $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int { + return $sink->write($write); + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!\is_array($options['proxy'])) { + $conf[\CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (isset($options['proxy']['no']) && Utils::isHostInNoProxy($host, $options['proxy']['no'])) { + unset($conf[\CURLOPT_PROXY]); + } else { + $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['crypto_method'])) { + if (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_0')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.0 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_0; + } elseif (\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_1')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.1 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_1; + } elseif (\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_2')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2; + } elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) { + if (!defined('CURL_SSLVERSION_TLSv1_3')) { + throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL'); + } + $conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3; + } else { + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!\file_exists($cert)) { + throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); + } + // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if (preg_match('#^(der|p12)$#i', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (\count($options['ssl_key']) === 2) { + [$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key']; + } else { + [$sslKey] = $options['ssl_key']; + } + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\file_exists($sslKey)) { + throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!\is_callable($progress)) { + throw new \InvalidArgumentException('progress client option must be callable'); + } + $conf[\CURLOPT_NOPROGRESS] = false; + $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) { + $progress($downloadSize, $downloaded, $uploadSize, $uploaded); + }; + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface + { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + .'providing an error. The request would have been retried, ' + .'but attempting to rewind the request body failed. ' + .'Exception: '.$e; + + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + .'and did not succeed. The most likely reason for the failure ' + .'is that cURL was unable to rewind the body of the request ' + .'and subsequent retries resulted in the same error. Turn on ' + .'the debug option to see what went wrong. See ' + .'https://bugs.php.net/bug.php?id=47204 for more information.'; + + return self::createRejection($easy, $ctx); + } else { + ++$easy->options['_curl_retries']; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy): callable + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return static function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = \trim($h); + if ($value === '') { + $startingResponse = true; + try { + $easy->createResponse(); + } catch (\Exception $e) { + $easy->createResponseException = $e; + + return -1; + } + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + + return \strlen($h); + }; + } + + public function __destruct() + { + foreach ($this->handles as $id => $handle) { + \curl_close($handle); + unset($this->handles[$id]); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 0000000..fe57ed5 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,25 @@ +factory = $options['handle_factory'] + ?? new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (isset($options['delay'])) { + \usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 0000000..a64e182 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,267 @@ + An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private $options = []; + + /** @var resource|\CurlMultiHandle */ + private $_mh; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); + + if (isset($options['select_timeout'])) { + $this->selectTimeout = $options['select_timeout']; + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { + @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); + $this->selectTimeout = (int) $selectTimeout; + } else { + $this->selectTimeout = 1; + } + + $this->options = $options['options'] ?? []; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->_mh); + } + + /** + * @param string $name + * + * @return resource|\CurlMultiHandle + * + * @throws \BadMethodCallException when another field as `_mh` will be gotten + * @throws \RuntimeException when curl can not initialize a multi handle + */ + public function __get($name) + { + if ($name !== '_mh') { + throw new \BadMethodCallException("Can not get other property as '_mh'."); + } + + $multiHandle = \curl_multi_init(); + + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + $this->_mh = $multiHandle; + + foreach ($this->options as $option => $value) { + // A warning is raised in case of a wrong option. + curl_multi_setopt($this->_mh, $option, $value); + } + + return $this->_mh; + } + + public function __destruct() + { + if (isset($this->_mh)) { + \curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { + return $this->cancel($id); + } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = Utils::currentTime(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + \curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) { + } + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $queue = P\Utils::queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + \usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry): void + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + \curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id): bool + { + if (!is_int($id)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + \curl_multi_remove_handle($this->_mh, $handle); + \curl_close($handle); + + return true; + } + + private function processMessages(): void + { + while ($done = \curl_multi_info_read($this->_mh)) { + if ($done['msg'] !== \CURLMSG_DONE) { + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 + continue; + } + $id = (int) $done['handle']; + \curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish($this, $entry['easy'], $this->factory) + ); + } + } + + private function timeToNext(): int + { + $currentTime = Utils::currentTime(); + $nextTime = \PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 0000000..1bc39f4 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,112 @@ +headers); + + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $status, + $headers, + $this->sink, + $ver, + $reason + ); + } + + /** + * @param string $name + * + * @return void + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name; + throw new \BadMethodCallException($msg); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 0000000..5554b8f --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,42 @@ +|null $queue The parameters to be passed to the append function, as an indexed array. + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param callable|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) + { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + \usleep((int) $options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + return $response->then( + function (?ResponseInterface $value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + + return P\Create::rejectionFor($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values + */ + public function append(...$values): void + { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0; + $stats = new TransferStats($request, $response, $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 0000000..f045b52 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,51 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', '0'); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed + || false !== \strpos($message, 'Connection refused') + || false !== \strpos($message, "couldn't connect to host") // error on HHVM + || false !== \strpos($message, 'connection attempt failed') + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } else { + $e = RequestException::wrapException($request, $e); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + return P\Create::rejectionFor($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + ?float $startTime, + ResponseInterface $response = null, + \Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); + ($options['on_stats'])($stats); + } + } + + /** + * @param resource $stream + */ + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface + { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\Utils::streamFor($stream); + $sink = $stream; + + if (\strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + try { + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) + ); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options): StreamInterface + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); + + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); + } + + /** + * @param resource $stream + */ + private function checkDecode(array $options, array $headers, $stream): array + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface + { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\Utils::copyToStream( + $source, + $sink, + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = []; + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line, + ]; + + return true; + }); + + try { + $resource = $callback(); + } finally { + \restore_error_handler(); + } + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value".\PHP_EOL; + } + } + throw new \RuntimeException(\trim($message)); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = \array_flip(\get_class_methods(__CLASS__)); + } + + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request); + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!\is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = \array_replace_recursive($context, $options['stream_context']); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { + $resource = @\fopen((string) $uri, 'r', false, $contextResource); + $this->lastHeaders = $http_response_header ?? []; + + if (false === $resource) { + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); + } + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + \stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options): UriInterface + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + + return $uri->withHost('['.$records[0]['ipv6'].']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request): array + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + 'ssl' => [ + 'peer_name' => $request->getUri()->getHost(), + ], + ]; + + $body = (string) $request->getBody(); + + if ('' !== $body) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header']); + + return $context; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void + { + $uri = null; + + if (!\is_array($value)) { + $uri = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { + $uri = $value[$scheme]; + } + } + } + + if (!$uri) { + return; + } + + $parsed = $this->parse_proxy($uri); + $options['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($options['http']['header'])) { + $options['http']['header'] = []; + } + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. + */ + private function parse_proxy(string $url): array + { + $parsed = \parse_url($url); + + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + if (isset($parsed['host']) && isset($parsed['port'])) { + $auth = null; + if (isset($parsed['user']) && isset($parsed['pass'])) { + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); + } + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", + 'auth' => $auth ? "Basic {$auth}" : null, + ]; + } + } + + // Return proxy as-is. + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void + { + if ( + $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT + || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT + || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) + ) { + $options['http']['crypto_method'] = $value; + + return; + } + + throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided'); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value !== true) { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void + { + if (\is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!\file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void + { + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value($total, $transferred, 0, 0); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = Utils::debugResource($value); + $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i].': "'.$v.'" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify, + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions) { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 0000000..6cb12f0 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,275 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return ResponseInterface|PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + + if ($this->handler !== null) { + $stack[] = '0) Handler: '.$this->debugCallable($this->handler); + } + + $result = ''; + foreach (\array_reverse($this->stack) as $tuple) { + ++$depth; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= 'Function: '.$this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (\array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!is_string($remove) && !is_callable($remove)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->cached = null; + $idx = \is_callable($remove) ? 0 : 1; + $this->stack = \array_values(\array_filter( + $this->stack, + static function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable(RequestInterface, array): PromiseInterface + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + foreach (\array_reverse($this->stack) as $fn) { + /** @var callable(RequestInterface, array): PromiseInterface $prev */ + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param callable|string $fn Function to write as a string. + */ + private function debugCallable($fn): string + { + if (\is_string($fn)) { + return "callable({$fn})"; + } + + if (\is_array($fn)) { + return \is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['".\get_class($fn[0])."', '{$fn[1]}'])"; + } + + /** @var object $fn */ + return 'callable('.\spl_object_hash($fn).')'; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 0000000..04e9eb3 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,199 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ResponseInterface $response = null, \Throwable $error = null): string + { + $cache = []; + + /** @var string */ + return \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + .' '.$request->getRequestTarget()) + .' HTTP/'.$request->getProtocolVersion()."\r\n" + .$this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + )."\r\n".$this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri()->__toString(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + + return $result; + }, + $this->template + ); + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name.': '.\implode(', ', $values)."\r\n"; + } + + return \trim($result); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 0000000..4793461 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,18 @@ +withCookieHeader($request); + + return $handler($request, $options) + ->then( + static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable(callable): callable Returns a function that accepts the next handler. + */ + public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ($request, array $options) use ($handler, $bodySummarizer) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + + return $handler($request, $options)->then( + static function (ResponseInterface $response) use ($request, $bodySummarizer) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, [], $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array|\ArrayAccess $container Container to hold the history (by reference). + * + * @return callable(callable): callable Returns a function that accepts the next handler. + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function (RequestInterface $request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + static function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options, + ]; + + return $value; + }, + static function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options, + ]; + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function (RequestInterface $request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable + { + // To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter + if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) { + throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class)); + } + + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + + return $response; + }, + static function ($reason) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof RequestException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Pool.php b/vendor/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 0000000..6277c61 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,125 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + /** + * Get promise + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see \GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch(ClientInterface $client, $requests, array $options = []): array + { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 0000000..0a8de81 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,105 @@ +nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void + { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 0000000..7aa21a6 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,228 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!\is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) + { + if (\strpos((string) $response->getStatusCode(), '3') !== 0 + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + // If authorization is handled by curl, unset it if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { + unset( + $options['curl'][\CURLOPT_HTTPAUTH], + $options['curl'][\CURLOPT_USERPWD] + ); + } + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + */ + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface + { + return $promise->then( + static function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects. + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void + { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface + { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 + || ($statusCode <= 302 && !$options['allow_redirects']['strict']) + ) { + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; + $requestMethod = $request->getMethod(); + + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; + $modify['body'] = ''; + } + + $uri = self::redirectUri($request, $response, $protocols); + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + $modify['uri'] = $uri; + Psr7\Message::rewindBody($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo(''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization and Cookie headers if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { + $modify['remove_headers'][] = 'Authorization'; + $modify['remove_headers'][] = 'Cookie'; + } + + return Psr7\Utils::modifyRequest($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header. + */ + private static function redirectUri( + RequestInterface $request, + ResponseInterface $response, + array $protocols + ): UriInterface { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($location->getScheme(), $protocols)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); + } + + return $location; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 0000000..a38768c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,274 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__.'::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @return int milliseconds. + */ + public static function exponentialDelay(int $retries): int + { + return (int) 2 ** ($retries - 1) * 1000; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ($value) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ($reason) use ($req, $options) { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface + { + $options['delay'] = ($this->delay)(++$options['retries'], $response, $request); + + return $this($request, $options); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/TransferStats.php b/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 0000000..2ce9e38 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,133 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Utils.php b/vendor/guzzlehttp/guzzle/src/Utils.php new file mode 100644 index 0000000..93d6d39 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Utils.php @@ -0,0 +1,384 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: '.implode(', ', $errors).')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // Replace URI only if the ASCII version is different + $uri = $uri->withHost($asciiHost); + } + } + + return $uri; + } + + /** + * @internal + */ + public static function getenv(string $name): ?string + { + if (isset($_SERVER[$name])) { + return (string) $_SERVER[$name]; + } + + if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) { + return (string) $value; + } + + return null; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/functions.php b/vendor/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 0000000..5edc66a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,167 @@ + +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +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/vendor/guzzlehttp/promises/README.md b/vendor/guzzlehttp/promises/README.md new file mode 100644 index 0000000..a32d3d2 --- /dev/null +++ b/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,559 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +## Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\Coroutine::of()`. + + +## Installation + +```shell +composer require guzzlehttp/promises +``` + + +## Version Guidance + +| Version | Status | PHP Version | +|---------|------------------------|--------------| +| 1.x | Bug and security fixes | >=5.5,<8.3 | +| 2.x | Latest | >=7.2.5,<8.4 | + + +## Quick Start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + +### Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promise triggers callbacks +registered with the promise's `then` method. These callbacks are triggered +only once and in the order in which they were added. + +### Resolving a Promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader." +$promise->resolve('reader.'); +``` + +### Promise Forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +### Promise Rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +### Rejection Forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + + +## Synchronous Wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + +### Unwrapping a Promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +## Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +## API + +### Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +### FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +### RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +## Promise Interoperability + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +### Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + + +## Implementation Notes + +### Promise Resolution and Chaining is Handled Iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + +### A Promise is the Deferred + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` + + +## Upgrading from Function API + +A static API was first introduced in 1.4.0, in order to mitigate problems with +functions conflicting between global and local copies of the package. The +function API was removed in 2.0.0. A migration table has been provided here for +your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/promises/composer.json b/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 0000000..6c5bdd6 --- /dev/null +++ b/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,58 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/vendor/guzzlehttp/promises/src/AggregateException.php b/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 0000000..40ffdbc --- /dev/null +++ b/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,19 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * + * @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function (): void { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + */ + public static function of(callable $generatorFn): self + { + return new self($generatorFn); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->result->otherwise($onRejected); + } + + public function wait(bool $unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState(): string + { + return $this->result->getState(); + } + + public function resolve($value): void + { + $this->result->resolve($value); + } + + public function reject($reason): void + { + $this->result->reject($reason); + } + + public function cancel(): void + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded): void + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value): void + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason): void + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/vendor/guzzlehttp/promises/src/Create.php b/vendor/guzzlehttp/promises/src/Create.php new file mode 100644 index 0000000..9d3fc4a --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Create.php @@ -0,0 +1,79 @@ +then([$promise, 'resolve'], [$promise, 'reject']); + + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Creates a rejected promise for a reason if the reason is not a promise. + * If the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + */ + public static function rejectionFor($reason): PromiseInterface + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + */ + public static function exceptionFor($reason): \Throwable + { + if ($reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for the given value. + * + * @param mixed $value + */ + public static function iterFor($value): \Iterator + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + return new \ArrayIterator([$value]); + } +} diff --git a/vendor/guzzlehttp/promises/src/Each.php b/vendor/guzzlehttp/promises/src/Each.php new file mode 100644 index 0000000..c09d23c --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Each.php @@ -0,0 +1,81 @@ + $onFulfilled, + 'rejected' => $onRejected, + ]))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + */ + public static function ofLimit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency, + ]))->promise(); + } + + /** + * Like limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + */ + public static function ofLimitAll( + $iterable, + $concurrency, + callable $onFulfilled = null + ): PromiseInterface { + return self::ofLimit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate): void { + $aggregate->reject($reason); + } + ); + } +} diff --git a/vendor/guzzlehttp/promises/src/EachPromise.php b/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 0000000..e123898 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,248 @@ +iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** @psalm-suppress InvalidNullableReturnType */ + public function promise(): PromiseInterface + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + /** @psalm-assert Promise $this->aggregate */ + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } + + /** + * @psalm-suppress NullableReturnStatement + */ + return $this->aggregate; + } + + private function createPromise(): void + { + $this->mutex = false; + $this->aggregate = new Promise(function (): void { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (Is::settled($this->aggregate)) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function (): void { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending(): void + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()) { + } + + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? ($this->concurrency)(count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()) { + } + } + + private function addPending(): bool + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key): void { + if ($this->onFulfilled) { + ($this->onFulfilled)( + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key): void { + if ($this->onRejected) { + ($this->onRejected)( + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator(): bool + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + + return false; + } + } + + private function step(int $idx): void + { + // If the promise was already resolved, then ignore this step. + if (Is::settled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished(): bool + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + + return true; + } + + return false; + } +} diff --git a/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 0000000..ab71296 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,89 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled): void { + if (Is::pending($p)) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + return $unwrap ? $this->value : null; + } + + public function getState(): string + { + return self::FULFILLED; + } + + public function resolve($value): void + { + if ($value !== $this->value) { + throw new \LogicException('Cannot resolve a fulfilled promise'); + } + } + + public function reject($reason): void + { + throw new \LogicException('Cannot reject a fulfilled promise'); + } + + public function cancel(): void + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/Is.php b/vendor/guzzlehttp/promises/src/Is.php new file mode 100644 index 0000000..f3f0503 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Is.php @@ -0,0 +1,40 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + */ + public static function settled(PromiseInterface $promise): bool + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + */ + public static function fulfilled(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + */ + public static function rejected(PromiseInterface $promise): bool + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/vendor/guzzlehttp/promises/src/Promise.php b/vendor/guzzlehttp/promises/src/Promise.php new file mode 100644 index 0000000..1b07bdc --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,281 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + + return $onFulfilled ? $promise->then($onFulfilled) : $promise; + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + } + + public function getState(): string + { + return $this->state; + } + + public function cancel(): void + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value): void + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason): void + { + $this->settle(self::REJECTED, $reason); + } + + private function settle(string $state, $value): void + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers): void { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise && Is::pending($value)) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers): void { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers): void { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler(int $index, $value, array $handler): void + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (Is::settled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending(): void + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + .'no internal wait function. You must provide a wait ' + .'function when constructing the promise to be able to ' + .'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn(): void + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Throwable $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList(): void + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/vendor/guzzlehttp/promises/src/PromiseInterface.php b/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 0000000..2824802 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,91 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ): PromiseInterface { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected): void { + if (Is::pending($p)) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected): PromiseInterface + { + return $this->then(null, $onRejected); + } + + public function wait(bool $unwrap = true) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState(): string + { + return self::REJECTED; + } + + public function resolve($value): void + { + throw new \LogicException('Cannot resolve a rejected promise'); + } + + public function reject($reason): void + { + if ($reason !== $this->reason) { + throw new \LogicException('Cannot reject a rejected promise'); + } + } + + public function cancel(): void + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/RejectionException.php b/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 0000000..72a81ba --- /dev/null +++ b/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,49 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: '.$description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: '.$this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: '.json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueue.php b/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 0000000..503e0b2 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,71 @@ +run(); + * + * @final + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct(bool $withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function (): void { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty(): bool + { + return !$this->queue; + } + + public function add(callable $task): void + { + $this->queue[] = $task; + } + + public function run(): void + { + while ($task = array_shift($this->queue)) { + /** @var callable $task */ + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown(): void + { + $this->enableShutdown = false; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 0000000..34c561a --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,24 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface|null $assign Optionally specify a new queue instance. + */ + public static function queue(TaskQueueInterface $assign = null): TaskQueueInterface + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a function to run in the task queue when it is next `run()` and + * returns a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + */ + public static function task(callable $task): PromiseInterface + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise): void { + try { + if (Is::pending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + $promise->reject($e); + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to resolve and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + */ + public static function inspect(PromiseInterface $promise): array + { + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait(), + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + */ + public static function inspectAll($promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = self::inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @throws \Throwable on error + */ + public static function unwrap($promises): array + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + */ + public static function all($promises, bool $recursive = false): PromiseInterface + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate): void { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use ($recursive, &$promises) { + foreach ($promises as $promise) { + if (Is::pending($promise)) { + return self::all($promises, $recursive); + } + } + + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + */ + public static function some(int $count, $promises): PromiseInterface + { + $results = []; + $rejections = []; + + return Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count): void { + if (Is::settled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections): void { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + + return array_values($results); + } + ); + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + */ + public static function any($promises): PromiseInterface + { + return self::some(1, $promises)->then(function ($values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + */ + public static function settle($promises): PromiseInterface + { + $results = []; + + return Each::of( + $promises, + function ($value, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results): void { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + + return $results; + }); + } +} diff --git a/vendor/guzzlehttp/psr7/CHANGELOG.md b/vendor/guzzlehttp/psr7/CHANGELOG.md new file mode 100644 index 0000000..fe3eda7 --- /dev/null +++ b/vendor/guzzlehttp/psr7/CHANGELOG.md @@ -0,0 +1,448 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## 2.6.2 - 2023-12-03 + +### Fixed + +- Fixed another issue with the fact that PHP transforms numeric strings in array keys to ints + +### Changed + +- Updated links in docs to their canonical versions +- Replaced `call_user_func*` with native calls + +## 2.6.1 - 2023-08-27 + +### Fixed + +- Properly handle the fact that PHP transforms numeric strings in array keys to ints + +## 2.6.0 - 2023-08-03 + +### Changed + +- Updated the mime type map to add some new entries, fix a couple of invalid entries, and remove an invalid entry +- Fallback to `application/octet-stream` if we are unable to guess the content type for a multipart file upload + +## 2.5.1 - 2023-08-03 + +### Fixed + +- Corrected mime type for `.acc` files to `audio/aac` + +### Changed + +- PHP 8.3 support + +## 2.5.0 - 2023-04-17 + +### Changed + +- Adjusted `psr/http-message` version constraint to `^1.1 || ^2.0` + +## 2.4.5 - 2023-04-17 + +### Fixed + +- Prevent possible warnings on unset variables in `ServerRequest::normalizeNestedFileSpec` +- Fixed `Message::bodySummary` when `preg_match` fails +- Fixed header validation issue + +## 2.4.4 - 2023-03-09 + +### Changed + +- Removed the need for `AllowDynamicProperties` in `LazyOpenStream` + +## 2.4.3 - 2022-10-26 + +### Changed + +- Replaced `sha1(uniqid())` by `bin2hex(random_bytes(20))` + +## 2.4.2 - 2022-10-25 + +### Fixed + +- Fixed erroneous behaviour when combining host and relative path + +## 2.4.1 - 2022-08-28 + +### Fixed + +- Rewind body before reading in `Message::bodySummary` + +## 2.4.0 - 2022-06-20 + +### Added + +- Added provisional PHP 8.2 support +- Added `UriComparator::isCrossOrigin` method + +## 2.3.0 - 2022-06-09 + +### Fixed + +- Added `Header::splitList` method +- Added `Utils::tryGetContents` method +- Improved `Stream::getContents` method +- Updated mimetype mappings + +## 2.2.2 - 2022-06-08 + +### Fixed + +- Fix `Message::parseRequestUri` for numeric headers +- Re-wrap exceptions thrown in `fread` into runtime exceptions +- Throw an exception when multipart options is misformatted + +## 2.2.1 - 2022-03-20 + +### Fixed + +- Correct header value validation + +## 2.2.0 - 2022-03-20 + +### Added + +- A more compressive list of mime types +- Add JsonSerializable to Uri +- Missing return types + +### Fixed + +- Bug MultipartStream no `uri` metadata +- Bug MultipartStream with filename for `data://` streams +- Fixed new line handling in MultipartStream +- Reduced RAM usage when copying streams +- Updated parsing in `Header::normalize()` + +## 2.1.1 - 2022-03-20 + +### Fixed + +- Validate header values properly + +## 2.1.0 - 2021-10-06 + +### Changed + +- Attempting to create a `Uri` object from a malformed URI will no longer throw a generic + `InvalidArgumentException`, but rather a `MalformedUriException`, which inherits from the former + for backwards compatibility. Callers relying on the exception being thrown to detect invalid + URIs should catch the new exception. + +### Fixed + +- Return `null` in caching stream size if remote size is `null` + +## 2.0.0 - 2021-06-30 + +Identical to the RC release. + +## 2.0.0@RC-1 - 2021-04-29 + +### Fixed + +- Handle possibly unset `url` in `stream_get_meta_data` + +## 2.0.0@beta-1 - 2021-03-21 + +### Added + +- PSR-17 factories +- Made classes final +- PHP7 type hints + +### Changed + +- When building a query string, booleans are represented as 1 and 0. + +### Removed + +- PHP < 7.2 support +- All functions in the `GuzzleHttp\Psr7` namespace + +## 1.8.1 - 2021-03-21 + +### Fixed + +- Issue parsing IPv6 URLs +- Issue modifying ServerRequest lost all its attributes + +## 1.8.0 - 2021-03-21 + +### Added + +- Locale independent URL parsing +- Most classes got a `@final` annotation to prepare for 2.0 + +### Fixed + +- Issue when creating stream from `php://input` and curl-ext is not installed +- Broken `Utils::tryFopen()` on PHP 8 + +## 1.7.0 - 2020-09-30 + +### Added + +- Replaced functions by static methods + +### Fixed + +- Converting a non-seekable stream to a string +- Handle multiple Set-Cookie correctly +- Ignore array keys in header values when merging +- Allow multibyte characters to be parsed in `Message:bodySummary()` + +### Changed + +- Restored partial HHVM 3 support + + +## [1.6.1] - 2019-07-02 + +### Fixed + +- Accept null and bool header values again + + +## [1.6.0] - 2019-06-30 + +### Added + +- Allowed version `^3.0` of `ralouphie/getallheaders` dependency (#244) +- Added MIME type for WEBP image format (#246) +- Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272) + +### Changed + +- Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262) +- Accept port number 0 to be valid (#270) + +### Fixed + +- Fixed subsequent reads from `php://input` in ServerRequest (#247) +- Fixed readable/writable detection for certain stream modes (#248) +- Fixed encoding of special characters in the `userInfo` component of an URI (#253) + + +## [1.5.2] - 2018-12-04 + +### Fixed + +- Check body size when getting the message summary + + +## [1.5.1] - 2018-12-04 + +### Fixed + +- Get the summary of a body only if it is readable + + +## [1.5.0] - 2018-12-03 + +### Added + +- Response first-line to response string exception (fixes #145) +- A test for #129 behavior +- `get_message_body_summary` function in order to get the message summary +- `3gp` and `mkv` mime types + +### Changed + +- Clarify exception message when stream is detached + +### Deprecated + +- Deprecated parsing folded header lines as per RFC 7230 + +### Fixed + +- Fix `AppendStream::detach` to not close streams +- `InflateStream` preserves `isSeekable` attribute of the underlying stream +- `ServerRequest::getUriFromGlobals` to support URLs in query parameters + + +Several other fixes and improvements. + + +## [1.4.2] - 2017-03-20 + +### Fixed + +- Reverted BC break to `Uri::resolve` and `Uri::removeDotSegments` by removing + calls to `trigger_error` when deprecated methods are invoked. + + +## [1.4.1] - 2017-02-27 + +### Added + +- Rriggering of silenced deprecation warnings. + +### Fixed + +- Reverted BC break by reintroducing behavior to automagically fix a URI with a + relative path and an authority by adding a leading slash to the path. It's only + deprecated now. + + +## [1.4.0] - 2017-02-21 + +### Added + +- Added common URI utility methods based on RFC 3986 (see documentation in the readme): + - `Uri::isDefaultPort` + - `Uri::isAbsolute` + - `Uri::isNetworkPathReference` + - `Uri::isAbsolutePathReference` + - `Uri::isRelativePathReference` + - `Uri::isSameDocumentReference` + - `Uri::composeComponents` + - `UriNormalizer::normalize` + - `UriNormalizer::isEquivalent` + - `UriResolver::relativize` + +### Changed + +- Ensure `ServerRequest::getUriFromGlobals` returns a URI in absolute form. +- Allow `parse_response` to parse a response without delimiting space and reason. +- Ensure each URI modification results in a valid URI according to PSR-7 discussions. + Invalid modifications will throw an exception instead of returning a wrong URI or + doing some magic. + - `(new Uri)->withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/vendor/guzzlehttp/psr7/LICENSE b/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..51c7ec8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +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/vendor/guzzlehttp/psr7/README.md b/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..850fa9d --- /dev/null +++ b/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,880 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + +![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg) +![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg) + + +## Features + +This package comes with a number of stream implementations and stream +decorators. + + +## Installation + +```shell +composer require guzzlehttp/psr7 +``` + +## Version Guidance + +| Version | Status | PHP Version | +|---------|---------------------|--------------| +| 1.x | Security fixes only | >=5.4,<8.1 | +| 2.x | Latest | >=7.2.5,<8.4 | + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + private $stream; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + ($this->callback)(); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::splitList` + +`public static function splitList(string|string[] $header): string[]` + +Splits a HTTP header defined to contain a comma-separated list into +each individual value: + +``` +$knownEtags = Header::splitList($request->getHeader('if-none-match')); +``` + +Example headers include `accept`, `cache-control` and `if-none-match`. + + +## `GuzzleHttp\Psr7\Header::normalize` (deprecated) + +`public static function normalize(string|array $header): array` + +`Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist) +which performs the same operation with a cleaned up API and improved +documentation. + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::tryGetContents` + +`public static function tryGetContents(resource $stream): string` + +Safely gets the contents of a given stream. + +When stream_get_contents fails, PHP normally raises a warning. This +function adds an error handler that checks for errors and throws an +exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://datatracker.ietf.org/doc/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://datatracker.ietf.org/doc/html/rfc3986#section-5.3). Usually this method does not need +to be called manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Cross-Origin Detection + +`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin. + +### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin` + +`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool` + +Determines if a modified URL should be considered cross-origin with respect to an original URL. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://datatracker.ietf.org/doc/html/rfc3986#section-5). This is for example also what web +browsers do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://datatracker.ietf.org/doc/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/vendor/guzzlehttp/psr7/composer.json b/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..70293fc --- /dev/null +++ b/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,93 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.36 || ^9.6.15" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/vendor/guzzlehttp/psr7/src/AppendStream.php b/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..ee8f378 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,248 @@ +addStream($stream); + } + } + + public function __toString(): string + { + try { + $this->rewind(); + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams + || ($this->current >= count($this->streams) - 1 + && $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + .$i.' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + */ + public function read($length): string + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + ++$this->current; + } + + $result = $this->streams[$this->current]->read($remaining); + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/vendor/guzzlehttp/psr7/src/BufferStream.php b/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..2b0eb77 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,147 @@ +hwm = $hwm; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length): string + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/vendor/guzzlehttp/psr7/src/CachingStream.php b/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..f34722c --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,153 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length): string + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close(): void + { + $this->remoteStream->close(); + $this->stream->close(); + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/vendor/guzzlehttp/psr7/src/DroppingStream.php b/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..6e3d209 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,49 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 0000000..3a08477 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private $methods; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_'.$name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + .'() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + ($this->_fn_close)(); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + try { + /** @var string */ + return ($this->_fn___toString)(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function close(): void + { + ($this->_fn_close)(); + } + + public function detach() + { + return ($this->_fn_detach)(); + } + + public function getSize(): ?int + { + return ($this->_fn_getSize)(); + } + + public function tell(): int + { + return ($this->_fn_tell)(); + } + + public function eof(): bool + { + return ($this->_fn_eof)(); + } + + public function isSeekable(): bool + { + return ($this->_fn_isSeekable)(); + } + + public function rewind(): void + { + ($this->_fn_rewind)(); + } + + public function seek($offset, $whence = SEEK_SET): void + { + ($this->_fn_seek)($offset, $whence); + } + + public function isWritable(): bool + { + return ($this->_fn_isWritable)(); + } + + public function write($string): int + { + return ($this->_fn_write)($string); + } + + public function isReadable(): bool + { + return ($this->_fn_isReadable)(); + } + + public function read($length): string + { + return ($this->_fn_read)($length); + } + + public function getContents(): string + { + return ($this->_fn_getContents)(); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return ($this->_fn_getMetadata)($key); + } +} diff --git a/vendor/guzzlehttp/psr7/src/Header.php b/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 0000000..bbce8b0 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,134 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @deprecated Use self::splitList() instead. + */ + public static function normalize($header): array + { + $result = []; + foreach ((array) $header as $value) { + foreach (self::splitList($value) as $parsed) { + $result[] = $parsed; + } + } + + return $result; + } + + /** + * Splits a HTTP header defined to contain a comma-separated list into + * each individual value. Empty values will be removed. + * + * Example headers include 'accept', 'cache-control' and 'if-none-match'. + * + * This method must not be used to parse headers that are not defined as + * a list, such as 'user-agent' or 'set-cookie'. + * + * @param string|string[] $values Header value as returned by MessageInterface::getHeader() + * + * @return string[] + */ + public static function splitList($values): array + { + if (!\is_array($values)) { + $values = [$values]; + } + + $result = []; + foreach ($values as $value) { + if (!\is_string($value)) { + throw new \TypeError('$header must either be a string or an array containing strings.'); + } + + $v = ''; + $isQuoted = false; + $isEscaped = false; + for ($i = 0, $max = \strlen($value); $i < $max; ++$i) { + if ($isEscaped) { + $v .= $value[$i]; + $isEscaped = false; + + continue; + } + + if (!$isQuoted && $value[$i] === ',') { + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + + $v = ''; + continue; + } + + if ($isQuoted && $value[$i] === '\\') { + $isEscaped = true; + $v .= $value[$i]; + + continue; + } + if ($value[$i] === '"') { + $isQuoted = !$isQuoted; + $v .= $value[$i]; + + continue; + } + + $v .= $value[$i]; + } + + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + } + + return $result; + } +} diff --git a/vendor/guzzlehttp/psr7/src/HttpFactory.php b/vendor/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 0000000..73d17e3 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,94 @@ +getSize(); + } + + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/vendor/guzzlehttp/psr7/src/InflateStream.php b/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..e674c9a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,37 @@ + 15 + 32]); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..f6c8490 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,49 @@ +filename = $filename; + $this->mode = $mode; + + // unsetting the property forces the first access to go through + // __get(). + unset($this->stream); + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/LimitStream.php b/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..fb22325 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,157 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit === -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function read($length): string + { + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Message.php b/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 0000000..5561a51 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,246 @@ +getMethod().' ' + .$message->getRequestTarget()) + .' HTTP/'.$message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: ".$message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/'.$message->getProtocolVersion().' ' + .$message->getStatusCode().' ' + .$message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (is_string($name) && strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: ".$value; + } + } else { + $msg .= "\r\n{$name}: ".implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n".$message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $body->rewind(); + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + [$rawHeaders, $body] = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + [$startLine, $rawHeaders] = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + $hostKey = array_filter(array_keys($headers), function ($k) { + // Numeric array keys are converted to int by PHP. + $k = (string) $k; + + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme.'://'.$host.'/'.ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + // the space between status-code and reason-phrase is required. But + // browsers accept responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: '.$data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + $parts[2] ?? null + ); + } +} diff --git a/vendor/guzzlehttp/psr7/src/MessageTrait.php b/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..65dbc4b --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,265 @@ + array of values */ + private $headers = []; + + /** @var string[] Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + public function withProtocolVersion($version): MessageInterface + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader($header): bool + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header): array + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header): string + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header): MessageInterface + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + + return $new; + } + + /** + * @param (string|string[])[] $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + // Numeric array keys are converted to int by PHP. + $header = (string) $header; + + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue($value): array + { + if (!is_array($value)) { + return $this->trimAndValidateHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimAndValidateHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4 + */ + private function trimAndValidateHeaderValues(array $values): array + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + $trimmed = trim((string) $value, " \t"); + $this->assertValue($trimmed); + + return $trimmed; + }, array_values($values)); + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * @param mixed $header + */ + private function assertHeader($header): void + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if (!preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header name.', $header) + ); + } + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + * + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * VCHAR = %x21-7E + * obs-text = %x80-FF + * obs-fold = CRLF 1*( SP / HTAB ) + */ + private function assertValue(string $value): void + { + // The regular expression intentionally does not support the obs-fold production, because as + // per RFC 7230#3.2.4: + // + // A sender MUST NOT generate a message that includes + // line folding (i.e., that has any field-value that contains a match to + // the obs-fold rule) unless the message is intended for packaging + // within the message/http media type. + // + // Clients must not send a request with line folding and a server sending folded headers is + // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting + // folding is not likely to break any legitimate use case. + if (!preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not valid header value.', $value) + ); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/MimeType.php b/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 0000000..b131bdb --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,1259 @@ + 'application/vnd.1000minds.decision-model+xml', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + '123' => 'application/vnd.lotus-1-2-3', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/vnd.nokia.n-gage.ac+xml', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'adts' => 'audio/aac', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/pdf', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'aml' => 'application/automationml-aml+xml', + 'amlx' => 'application/automationml-amlx+zip', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'appinstaller' => 'application/appinstaller', + 'application' => 'application/x-ms-application', + 'appx' => 'application/appx', + 'appxbundle' => 'application/appxbundle', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/x-au', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdoc' => 'application/x-bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btf' => 'image/prs.btif', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdr' => 'application/cdr', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/octet-stream', + 'cld' => 'model/vnd.cld', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cwl' => 'application/cwl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dib' => 'image/bmp', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dpx' => 'image/dpx', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gpg' => 'application/gpg-keys', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hsj2' => 'image/hsj2', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'video/jpm', + 'jpx' => 'image/jpx', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jt' => 'model/jt', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/x-iwork-keynote-sffkey', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'text/plain', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/x-m4a', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'application/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm21' => 'application/mp21', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'text/javascript', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mp21' => 'application/mp21', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msix' => 'application/msix', + 'msixbundle' => 'application/msixbundle', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/x-iwork-numbers-sffnumbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'text/x-org', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/x-iwork-pages-sffpages', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/x-pilot', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'application/x-photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyo' => 'model/vnd.pytha.pyox', + 'pyox' => 'model/vnd.pytha.pyox', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/x-rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/octet-stream', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'step' => 'application/STEP', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stp' => 'application/STEP', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/x-tar', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'u32' => 'application/x-authorware-bin', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uo' => 'application/vnd.uoml+xml', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usda' => 'model/vnd.usda', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vlc' => 'application/videolan', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgsl' => 'text/wgsl', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x32' => 'application/x-authorware-bin', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtm' => 'application/vnd.pwg-xhtml-print+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsf' => 'application/prs.xsf+xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * Determines the mimetype of a file by looking at its extension. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extensions to a mimetype. + * + * @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[strtolower($extension)] ?? null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/MultipartStream.php b/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..d23fba8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,165 @@ +boundary = $boundary ?: bin2hex(random_bytes(20)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param string[] $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n".trim($str)."\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + if (!is_array($element)) { + throw new \UnexpectedValueException('An array is expected'); + } + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + /** + * @param string[] $headers + * + * @return array{0: StreamInterface, 1: string[]} + */ + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + // Set a default content-disposition header if one was no provided + $disposition = self::getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = self::getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = self::getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + $headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream'; + } + + return [$stream, $headers]; + } + + /** + * @param string[] $headers + */ + private static function getHeader(array $headers, string $key): ?string + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower((string) $k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..161a224 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,28 @@ +source = $source; + $this->size = $options['size'] ?? null; + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __toString(): string + { + try { + return Utils::copyToString($this); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read($length): string + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents(): string + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source !== null) { + do { + $data = ($this->source)($length); + if ($data === false || $data === null) { + $this->source = null; + + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Query.php b/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 0000000..8b94927 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', (string) $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!array_key_exists($key, $result)) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? (int) $v : $v; + if ($v !== null) { + $qs .= '='.$encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? (int) $vv : $vv; + if ($vv !== null) { + $qs .= '='.$encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Request.php b/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..faafe1a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,159 @@ +assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target === '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?'.$this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget): RequestInterface + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod($method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':'.$port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + /** + * @param mixed $method + */ + private function assertMethod($method): void + { + if (!is_string($method) || $method === '') { + throw new InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Response.php b/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..00f16e2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,161 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase; + + /** @var int */ + private $statusCode; + + /** + * @param int $status Status code + * @param (string|string[])[] $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + string $reason = null + ) { + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $this->reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + + return $new; + } + + /** + * @param mixed $statusCode + */ + private function assertStatusCodeIsInteger($statusCode): void + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Rfc7230.php b/vendor/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 0000000..8219dba --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,23 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/vendor/guzzlehttp/psr7/src/ServerRequest.php b/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..3cc9534 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,340 @@ +serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileInterface[] + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key] ?? null, + 'error' => $files['error'][$key] ?? null, + 'name' => $files['name'][$key] ?? null, + 'type' => $files['type'][$key] ?? null, + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority(string $authority): array + { + $uri = 'http://'.$authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = $parts['host'] ?? null; + $port = $parts['port'] ?? null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + [$host, $port] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams(array $cookies): ServerRequestInterface + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * @return mixed + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + public function withAttribute($attribute, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + public function withoutAttribute($attribute): ServerRequestInterface + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Stream.php b/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..0aff9b2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,283 @@ +size = $options['size']; + } + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool) preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool) preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return Utils::tryGetContents($this->stream); + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (is_array($stats) && isset($stats['size'])) { + $this->size = $stats['size']; + + return $this->size; + } + + return null; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + .$offset.' with whence '.var_export($whence, true)); + } + } + + public function read($length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + try { + $string = fread($this->stream, $length); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to read from stream', 0, $e); + } + + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..601c13a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,156 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @return StreamInterface + */ + public function __get(string $name) + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + + return ''; + } + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = ($callable)(...$args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * @return mixed + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..ae85388 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,203 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + .'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream], + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read(int $count): string + { + return $this->stream->read($count); + } + + public function stream_write(string $data): int + { + return $this->stream->write($data); + } + + public function stream_tell(): int + { + return $this->stream->tell(); + } + + public function stream_eof(): bool + { + return $this->stream->eof(); + } + + public function stream_seek(int $offset, int $whence): bool + { + $this->stream->seek($offset, $whence); + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + $stream = clone $this->stream; + $resource = $stream->detach(); + + return $resource ?? false; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + public function stream_stat(): array + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188, + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } + + /** + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + ]; + } +} diff --git a/vendor/guzzlehttp/psr7/src/UploadedFile.php b/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..b267199 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,211 @@ +setError($errorStatus); + $this->size = $size; + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (false === in_array($error, UploadedFile::ERRORS, true)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + private static function isStringNotEmpty($param): bool + { + return is_string($param) && false === empty($param); + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo($targetPath): void + { + $this->validateActive(); + + if (false === self::isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Uri.php b/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..f1feee8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,743 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + /** + * Unreserved characters for use in a regex. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.3 + */ + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; + + /** + * Sub-delims for use in a regex. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 + */ + private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** @var string|null String representation */ + private $composedComponents; + + public function __construct(string $uri = '') + { + if ($uri !== '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new MalformedUriException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @return array|false + */ + private static function parse(string $url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + /** @var array{0:string, 1:string, 2:string} $matches */ + $prefix = $matches[1]; + $url = $matches[2]; + } + + /** @var string */ + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix.$encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString(): string + { + if ($this->composedComponents === null) { + $this->composedComponents = self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + return $this->composedComponents; + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme.':'; + } + + if ($authority != '' || $scheme === 'file') { + $uri .= '//'.$authority; + } + + if ($authority != '' && $path != '' && $path[0] != '/') { + $path = '/'.$path; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?'.$query; + } + + if ($fragment != '') { + $uri .= '#'.$fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param (string|null)[] $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @see https://www.php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts(array $parts): UriInterface + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo.'@'.$authority; + } + + if ($this->port !== null) { + $authority .= ':'.$this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + return $this->path; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null): UriInterface + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':'.$this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withHost($host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withQuery($query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + $new->composedComponents = null; + + return $new; + } + + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + $new->composedComponents = null; + + return $new; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts): void + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param mixed $scheme + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $component + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component): string + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param mixed $host + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host): string + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port): ?int + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xFFFF < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param (string|int)[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map(function ($k): string { + return rawurldecode((string) $k); + }, $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param mixed $path + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path): string + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param mixed $str + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str): string + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriComparator.php b/vendor/guzzlehttp/psr7/src/UriComparator.php new file mode 100644 index 0000000..70c582a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriComparator.php @@ -0,0 +1,52 @@ +getHost(), $modified->getHost()) !== 0) { + return true; + } + + if ($original->getScheme() !== $modified->getScheme()) { + return true; + } + + if (self::computePort($original) !== self::computePort($modified)) { + return true; + } + + return false; + } + + private static function computePort(UriInterface $uri): int + { + $port = $uri->getPort(); + + if (null !== $port) { + return $port; + } + + return 'https' === $uri->getScheme() ? 443 : 80; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..e174557 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,220 @@ +getPath() === '' + && ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match): string { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match): string { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriResolver.php b/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..3737be1 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,211 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/'.$rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1).$rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' + && ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)).implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/Utils.php b/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 0000000..bf5ea9d --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,463 @@ + $v) { + if (!in_array(strtolower((string) $k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':'.$port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, (string) $resource); + fseek($stream, 0); + } + + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + stream_copy_to_stream($resource, $stream); + fseek($stream, 0); + $resource = $stream; + } + + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $errstr + )); + + return true; + }); + + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Safely gets the contents of a given stream. + * + * When stream_get_contents fails, PHP normally raises a warning. This + * function adds an error handler that checks for errors and throws an + * exception instead. + * + * @param resource $stream + * + * @throws \RuntimeException if the stream cannot be read + */ + public static function tryGetContents($stream): string + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $errstr + )); + + return true; + }); + + try { + /** @var string|false $contents */ + $contents = stream_get_contents($stream); + + if ($contents === false) { + $ex = new \RuntimeException('Unable to read stream contents'); + } + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $contents; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/vendor/psr/cache/CHANGELOG.md b/vendor/psr/cache/CHANGELOG.md new file mode 100644 index 0000000..58ddab0 --- /dev/null +++ b/vendor/psr/cache/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Fixed + +- Make spacing consistent in phpdoc annotations php-fig/cache#9 - chalasr +- Fix grammar in phpdoc annotations php-fig/cache#10 - chalasr +- Be more specific in docblocks that `getItems()` and `deleteItems()` take an array of strings (`string[]`) compared to just `array` php-fig/cache#8 - GrahamCampbell +- For `expiresAt()` and `expiresAfter()` in CacheItemInterface fix docblock to specify null as a valid parameters as well as an implementation of DateTimeInterface php-fig/cache#7 - GrahamCampbell + +## 1.0.0 - 2015-12-11 + +Initial stable release; reflects accepted PSR-6 specification diff --git a/vendor/psr/cache/LICENSE.txt b/vendor/psr/cache/LICENSE.txt new file mode 100644 index 0000000..b1c2c97 --- /dev/null +++ b/vendor/psr/cache/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2015 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/vendor/psr/cache/README.md b/vendor/psr/cache/README.md new file mode 100644 index 0000000..9855a31 --- /dev/null +++ b/vendor/psr/cache/README.md @@ -0,0 +1,12 @@ +Caching Interface +============== + +This repository holds all interfaces related to [PSR-6 (Caching Interface)][psr-url]. + +Note that this is not a Caching implementation of its own. It is merely interfaces that describe the components of a Caching mechanism. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: https://www.php-fig.org/psr/psr-6/ +[package-url]: https://packagist.org/packages/psr/cache +[implementation-url]: https://packagist.org/providers/psr/cache-implementation diff --git a/vendor/psr/cache/composer.json b/vendor/psr/cache/composer.json new file mode 100644 index 0000000..4b68797 --- /dev/null +++ b/vendor/psr/cache/composer.json @@ -0,0 +1,25 @@ +{ + "name": "psr/cache", + "description": "Common interface for caching libraries", + "keywords": ["psr", "psr-6", "cache"], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "Psr\\Cache\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/cache/src/CacheException.php b/vendor/psr/cache/src/CacheException.php new file mode 100644 index 0000000..bb785f4 --- /dev/null +++ b/vendor/psr/cache/src/CacheException.php @@ -0,0 +1,10 @@ +=7.0.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-factory/src/RequestFactoryInterface.php b/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 0000000..cb39a08 --- /dev/null +++ b/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ + `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + diff --git a/vendor/psr/http-message/docs/PSR7-Usage.md b/vendor/psr/http-message/docs/PSR7-Usage.md new file mode 100644 index 0000000..b6d048a --- /dev/null +++ b/vendor/psr/http-message/docs/PSR7-Usage.md @@ -0,0 +1,159 @@ +### PSR-7 Usage + +All PSR-7 applications comply with these interfaces +They were created to establish a standard between middleware implementations. + +> `RequestInterface`, `ServerRequestInterface`, `ResponseInterface` extend `MessageInterface` because the `Request` and the `Response` are `HTTP Messages`. +> When using `ServerRequestInterface`, both `RequestInterface` and `Psr\Http\Message\MessageInterface` methods are considered. + + +The following examples will illustrate how basic operations are done in PSR-7. + +##### Examples + + +For this examples to work (at least) a PSR-7 implementation package is required. (eg: zendframework/zend-diactoros, guzzlehttp/psr7, slim/slim, etc) +All PSR-7 implementations should have the same behaviour. + +The following will be assumed: +`$request` is an object of `Psr\Http\Message\RequestInterface` and + +`$response` is an object implementing `Psr\Http\Message\RequestInterface` + + +### Working with HTTP Headers + +#### Adding headers to response: + +```php +$response->withHeader('My-Custom-Header', 'My Custom Message'); +``` + +#### Appending values to headers + +```php +$response->withAddedHeader('My-Custom-Header', 'The second message'); +``` + +#### Checking if header exists: + +```php +$request->hasHeader('My-Custom-Header'); // will return false +$response->hasHeader('My-Custom-Header'); // will return true +``` + +> Note: My-Custom-Header was only added in the Response + +#### Getting comma-separated values from a header (also applies to request) + +```php +// getting value from request headers +$request->getHeaderLine('Content-Type'); // will return: "text/html; charset=UTF-8" +// getting value from response headers +$response->getHeaderLine('My-Custom-Header'); // will return: "My Custom Message; The second message" +``` + +#### Getting array of value from a header (also applies to request) +```php +// getting value from request headers +$request->getHeader('Content-Type'); // will return: ["text/html", "charset=UTF-8"] +// getting value from response headers +$response->getHeader('My-Custom-Header'); // will return: ["My Custom Message", "The second message"] +``` + +#### Removing headers from HTTP Messages +```php +// removing a header from Request, removing deprecated "Content-MD5" header +$request->withoutHeader('Content-MD5'); + +// removing a header from Response +// effect: the browser won't know the size of the stream +// the browser will download the stream till it ends +$response->withoutHeader('Content-Length'); +``` + +### Working with HTTP Message Body + +When working with the PSR-7 there are two methods of implementation: +#### 1. Getting the body separately + +> This method makes the body handling easier to understand and is useful when repeatedly calling body methods. (You only call `getBody()` once). Using this method mistakes like `$response->write()` are also prevented. + +```php +$body = $response->getBody(); +// operations on body, eg. read, write, seek +// ... +// replacing the old body +$response->withBody($body); +// this last statement is optional as we working with objects +// in this case the "new" body is same with the "old" one +// the $body variable has the same value as the one in $request, only the reference is passed +``` + +#### 2. Working directly on response + +> This method is useful when only performing few operations as the `$request->getBody()` statement fragment is required + +```php +$response->getBody()->write('hello'); +``` + +### Getting the body contents + +The following snippet gets the contents of a stream contents. +> Note: Streams must be rewinded, if content was written into streams, it will be ignored when calling `getContents()` because the stream pointer is set to the last character, which is `\0` - meaning end of stream. +```php +$body = $response->getBody(); +$body->rewind(); // or $body->seek(0); +$bodyText = $body->getContents(); +``` +> Note: If `$body->seek(1)` is called before `$body->getContents()`, the first character will be ommited as the starting pointer is set to `1`, not `0`. This is why using `$body->rewind()` is recommended. + +### Append to body + +```php +$response->getBody()->write('Hello'); // writing directly +$body = $request->getBody(); // which is a `StreamInterface` +$body->write('xxxxx'); +``` + +### Prepend to body +Prepending is different when it comes to streams. The content must be copied before writing the content to be prepended. +The following example will explain the behaviour of streams. + +```php +// assuming our response is initially empty +$body = $repsonse->getBody(); +// writing the string "abcd" +$body->write('abcd'); + +// seeking to start of stream +$body->seek(0); +// writing 'ef' +$body->write('ef'); // at this point the stream contains "efcd" +``` + +#### Prepending by rewriting separately + +```php +// assuming our response body stream only contains: "abcd" +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // abcd +// seeking the stream to beginning +$body->rewind(); +$body->write('ef'); // stream contains "efcd" +$body->write($contents); // stream contains "efabcd" +``` + +> Note: `getContents()` seeks the stream while reading it, therefore if the second `rewind()` method call was not present the stream would have resulted in `abcdefabcd` because the `write()` method appends to stream if not preceeded by `rewind()` or `seek(0)`. + +#### Prepending by using contents as a string +```php +$body = $response->getBody(); +$body->rewind(); +$contents = $body->getContents(); // efabcd +$contents = 'ef'.$contents; +$body->rewind(); +$body->write($contents); +``` diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..a83c985 --- /dev/null +++ b/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(): array; + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader(string $name): bool; + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader(string $name): array; + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine(string $name): string; + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader(string $name, $value): MessageInterface; + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader(string $name, $value): MessageInterface; + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader(string $name): MessageInterface; + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(): StreamInterface; + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body): MessageInterface; +} diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..33f85e5 --- /dev/null +++ b/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,130 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(): array; + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query): ServerRequestInterface; + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(): array; + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface; + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data): ServerRequestInterface; + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(): array; + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute(string $name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute(string $name, $value): ServerRequestInterface; + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute(string $name): ServerRequestInterface; +} diff --git a/vendor/psr/http-message/src/StreamInterface.php b/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..a62aabb --- /dev/null +++ b/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(): string; + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(): string; + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(): string; + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(): ?int; + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(): string; + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(): string; + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(): string; + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme(string $scheme): UriInterface; + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo(string $user, ?string $password = null): UriInterface; + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost(string $host): UriInterface; + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort(?int $port): UriInterface; + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath(string $path): UriInterface; + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery(string $query): UriInterface; + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment(string $fragment): UriInterface; + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(): string; +} diff --git a/vendor/ralouphie/getallheaders/LICENSE b/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 0000000..be5540c --- /dev/null +++ b/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +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/vendor/ralouphie/getallheaders/README.md b/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 0000000..9430d76 --- /dev/null +++ b/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/vendor/ralouphie/getallheaders/composer.json b/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 0000000..de8ce62 --- /dev/null +++ b/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/vendor/ralouphie/getallheaders/src/getallheaders.php b/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 0000000..c7285a5 --- /dev/null +++ b/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/vendor/squizlabs/php_codesniffer/CHANGELOG.md b/vendor/squizlabs/php_codesniffer/CHANGELOG.md new file mode 100644 index 0000000..2da2e81 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/CHANGELOG.md @@ -0,0 +1,5721 @@ +# Changelog +The file documents changes to the PHP_CodeSniffer project. + +## [Unreleased] + +_Nothing yet._ + + +## [3.8.1] - 2024-01-11 + +### Added +- Documentation has been added for the following sniffs: + - Generic.CodeAnalysis.EmptyPHPStatement + - Generic.Formatting.SpaceBeforeCast + - Generic.PHP.Syntax + - Generic.WhiteSpace.LanguageConstructSpacing + - PSR12.Classes.ClosingBrace + - PSR12.Classes.OpeningBraceSpace + - PSR12.ControlStructures.BooleanOperatorPlacement + - PSR12.Files.OpenTag + - Thanks to [Rodrigo Primo][@rodrigoprimo] and [Denis Žoljom][@dingo-d] for the patches + +### Changed +- GitHub releases will now always only contain unversioned release assets (PHARS + asc files) (same as it previously was in the squizlabs repo). See [#205] for context. + - Thanks to [Shivam Mathur][@shivammathur] for opening a discussion about this +- Various housekeeping, includes improvements to the tests and documentation + - Thanks to [Dan Wallis][@fredden], [Lucas Hoffmann][@lucc], [Rodrigo Primo][@rodrigoprimo] and [Juliette Reinders Folmer][@jrfnl] for their contributions + +### Fixed +- Fixed bug [#124] : Report Full : avoid unnecessarily wrapping lines when `-s` is used + - Thanks to [Brad Jorsch][@anomiex] for the patch +- Fixed bug [#124] : Report Full : fix incorrect bolding of pipes when `-s` is used and messages wraps + - Thanks to [Brad Jorsch][@anomiex] for the patch +- Fixed bug [#150] : Squiz.WhiteSpace.KeywordSpacing : prevent a PHP notice when run during live coding + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#154] : Report Full : delimiter line calculation could go wonky on wide screens when a report contains multi-line messages + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#178] : Squiz.Commenting.VariableComment : docblocks were incorrectly being flagged as missing when a property declaration used PHP native union/intersection type declarations + - Thanks to [Ferdinand Kuhl][@fcool] for the patch +- Fixed bug [#211] : Squiz.Commenting.VariableComment : docblocks were incorrectly being flagged as missing when a property declaration used PHP 8.2+ stand-alone `true`/`false`/`null` type declarations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#211] : Squiz.Commenting.VariableComment : docblocks were incorrectly being flagged as missing when a property declaration used PHP native `parent`, `self` or a namespace relative class name type declaration + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#226] : Generic.CodeAnalysis.ForLoopShouldBeWhileLoop : prevent a potential PHP 8.3 deprecation notice during live coding + - Thanks to [Rodrigo Primo][@rodrigoprimo] for the patch + +[#124]: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/124 +[#150]: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/150 +[#154]: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/154 +[#178]: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/178 +[#205]: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/205 +[#211]: https://github.com/PHPCSStandards/PHP_CodeSniffer/pull/211 +[#226]: https://github.com/PHPCSStandards/PHP_CodeSniffer/pull/226 + + +## [3.8.0] - 2023-12-08 + +[Squizlabs/PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) is dead. Long live [PHPCSStandards/PHP_CodeSniffer](https://github.com/PHPCSStandards/PHP_CodeSniffer)! + +### Breaking Changes +- The `squizlabs/PHP_CodeSniffer` repository has been abandoned. The `PHPCSStandards/PHP_CodeSniffer` repository will serve as the continuation of the project. For more information about this change, please read the [announcement](https://github.com/squizlabs/PHP_CodeSniffer/issues/3932). + - Installation of PHP_CodeSniffer via PEAR is no longer supported. + - Users will need to switch to another installation method. + - Note: this does not affect the PEAR sniffs. + - For Composer users, nothing changes. + - **_In contrast to earlier information, the `squizlabs/php_codesniffer` package now points to the new repository and everything will continue to work as before._** + - PHIVE users may need to clear the PHIVE URL cache. + - PHIVE users who don't use the package alias, but refer to the package URL, will need to update the URL from `https://squizlabs.github.io/PHP_CodeSniffer/phars/` to `https://phars.phpcodesniffer.com/phars/`. + - Users who download the PHAR files using curl or wget, will need to update the download URL from `https://squizlabs.github.io/PHP_CodeSniffer/[phpcs|phpcbf].phar` or `https://github.com/squizlabs/PHP_CodeSnifffer/releases/latest/download/[phpcs|phpcbf].phar` to `https://phars.phpcodesniffer.com/[phpcs|phpcbf].phar`. + - For users who install PHP_CodeSniffer via the [setup-php](https://github.com/shivammathur/setup-php/) action runner for GitHub Actions, nothing changes. + - Users using a git clone will need to update the clone address from `git@github.com:squizlabs/PHP_CodeSniffer.git` to `git@github.com:PHPCSStandards/PHP_CodeSniffer.git`. + - Contributors will need to fork the new repo and add both the new fork as well as the new repo as remotes to their local git copy of PHP_CodeSniffer. + - Users who have (valid) open issues or pull requests in the `squizlabs/PHP_CodeSniffer` repository are invited to resubmit these to the `PHPCSStandards/PHP_CodeSniffer` repository. + +### Added +- Runtime support for PHP 8.3. All known PHP 8.3 deprecation notices have been fixed + - Syntax support for new PHP 8.3 features will follow in a future release + - If you find any PHP 8.3 deprecation notices which were missed, please report them + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patches +- Added support for PHP 8.2 readonly classes to File::getClassProperties() through a new is_readonly array index in the return value + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.2 readonly classes to a number of sniffs + - Generic.CodeAnalysis.UnnecessaryFinalModifier + - PEAR.Commenting.ClassComment + - PEAR.Commenting.FileComment + - PSR1.Files.SideEffects + - PSR2.Classes.ClassDeclaration + - PSR12.Files.FileHeader + - Squiz.Classes.ClassDeclaration + - Squiz.Classes.LowercaseClassKeywords + - Squiz.Commenting.ClassComment + - Squiz.Commenting.DocCommentAlignment + - Squiz.Commenting.FileComment + - Squiz.Commenting.InlineComment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.2 `true` as a stand-alone type declaration + - The `File::getMethodProperties()`, `File::getMethodParameters()` and `File::getMemberProperties()` methods now all support the `true` type + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.2 `true` as a stand-alone type to a number of sniffs + - Generic.PHP.LowerCaseType + - PSr12.Functions.NullableTypeDeclaration + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added a Performance report to allow for finding "slow" sniffs + - To run this report, run PHPCS with --report=Performance. + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.RequireStrictTypes : new warning for when there is a declare statement, but the strict_types directive is set to 0 + - The warning can be turned off by excluding the `Generic.PHP.RequireStrictTypes.Disabled` error code + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.FunctionComment : new `ParamNameUnexpectedAmpersandPrefix` error for parameters annotated as passed by reference while the parameter is not passed by reference + - Thanks to [Dan Wallis][@fredden] for the patch +- Documentation has been added for the following sniffs: + - PSR2.Files.ClosingTag + - PSR2.Methods.FunctionCallSignature + - PSR2.Methods.FunctionClosingBrace + - Thanks to [Atsushi Okui][@blue32a] for the patch +- Support for PHPUnit 8 and 9 to the test suite + - Test suites for external standards which run via the PHPCS native test suite can now run on PHPUnit 4-9 (was 4-7) + - If any of these tests use the PHPUnit `setUp()`/`tearDown()` methods or overload the `setUp()` in the `AbstractSniffUnitTest` test case, they will need to be adjusted. See the [PR details for further information](https://github.com/PHPCSStandards/PHP_CodeSniffer/pull/59/commits/26384ebfcc0b1c1651b0e1e40c9b6c8c22881832) + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Changed +- Changes have been made to the way PHPCS handles invalid sniff properties being set in a custom ruleset + - Fixes PHP 8.2 deprecation notices for properties set in a (custom) ruleset for complete standards/complete sniff categories + - Invalid sniff properties set for individual sniffs will now result in an error and halt the execution of PHPCS + - A descriptive error message is provided to allow users to fix their ruleset + - Sniff properties set for complete standards/complete sniff categories will now only be set on sniffs which explicitly support the property + - The property will be silently ignored for those sniffs which do not support the property + - Invalid sniff properties set for sniffs via inline annotations will result in an informative `Internal.PropertyDoesNotExist` errror on line 1 of the scanned file, but will not halt the execution of PHPCS + - For sniff developers, it is strongly recommended for sniffs to explicitly declare any user-adjustable public properties + - If dynamic properties need to be supported for a sniff, either declare the magic __set()/__get()/__isset()/__unset() methods on the sniff or let the sniff extend stdClass + - Note: The #[\AllowDynamicProperties] attribute will have no effect for properties which are being set in rulesets + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The third parameter for the Ruleset::setSniffProperty() method has been changed to expect an array + - Sniff developers/integrators of PHPCS may need to make some small adjustments to allow for this change + - Existing code will continue to work but will throw a deprecation error + - The backwards compatiblity layer will be removed in PHPCS 4.0 + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- When using `auto` report width (the default) a value of 80 columns will be used if the width cannot be determined + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Sniff error messages are now more informative to help bugs get reported to the correct project + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.CodeAnalysis.UnusedFunctionParameter will now ignore magic methods for which the signature is defined by PHP + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Functions.OpeningFunctionBraceBsdAllman will now check the brace indent before the opening brace for empty functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Functions.OpeningFunctionBraceKernighanRitchie will now check the spacing before the opening brace for empty functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.IncrementDecrementSpacing now detects more spacing issues + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PSR2.Classes.PropertyDeclaration now enforces that the readonly modifier comes after the visibility modifier + - PSR2 and PSR12 do not have documented rules for this as they pre-date the readonly modifier + - PSR-PER has been used to confirm the order of this keyword so it can be applied to PSR2 and PSR12 correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Commenting.FunctionComment + Squiz.Commenting.FunctionComment: the SpacingAfter error can now be auto-fixed + - Thanks to [Dan Wallis][@fredden] for the patch +- Squiz.PHP.InnerFunctions sniff no longer reports on OO methods for OO structures declared within a function or closure + - Thanks to [@Daimona] for the patch +- Squiz.PHP.NonExecutableCode will now also flag redundant return statements just before a closure close brace + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Runtime performance improvement for PHPCS CLI users. The improvement should be most noticeable for users on Windows. + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The following sniffs have received performance related improvements: + - Generic.PHP.LowerCaseConstant + - Generic.PHP.LowerCaseType + - PSR12.Files.OpenTag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patches +- The -e (explain) command will now list sniffs in natural order + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Tests using the PHPCS native test framework with multiple test case files will now run the test case files in numeric order. + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The following sniffs have received minor message readability improvements: + - Generic.Arrays.ArrayIndent + - Generic.Formatting.SpaceAfterCast + - Generic.Formatting.SpaceAfterNot + - Generic.WhiteSpace.SpreadOperatorSpacingAfter + - Squiz.Arrays.ArrayDeclaration + - Squiz.Commenting.DocCommentAlignment + - Squiz.ControlStructures.ControlSignature + - Thanks to [Danny van der Sluijs][@DannyvdSluijs] and [Juliette Reinders Folmer][@jrfnl] for the patches +- Improved README syntax highlighting + - Thanks to [Benjamin Loison][@Benjamin-Loison] for the patch +- Various documentation improvements + - Thanks to [Andrew Dawes][@AndrewDawes], [Danny van der Sluijs][@DannyvdSluijs] and [Juliette Reinders Folmer][@jrfnl] for the patches + +### Removed +- Removed support for installation via PEAR + - Use composer or the PHAR files instead + +### Fixed +- Fixed bug [#2857] : Squiz/NonExecutableCode: prevent false positives when exit is used in a ternary expression or as default with null coalesce + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3386] : PSR1/SideEffects : improved recognition of disable/enable annotations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3557] : Squiz.Arrays.ArrayDeclaration will now ignore PHP 7.4 array unpacking when determining whether an array is associative + - Thanks to [Volker Dusch][@edorian] for the patch +- Fixed bug [#3592] : Squiz/NonExecutableCode: prevent false positives when a PHP 8.0+ inline throw expression is encountered + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3715] : Generic/UnusedFunctionParameter: fixed incorrect errorcode for closures/arrow functions nested within extended classes/classes which implement + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3717] : Squiz.Commenting.FunctionComment: fixed false positive for `InvalidNoReturn` when type is never + - Thanks to [Choraimy Kroonstuiver][@axlon] for the patch +- Fixed bug [#3720] : Generic/RequireStrictTypes : will now bow out silently in case of parse errors/live coding instead of throwing false positives/false negatives + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3720] : Generic/RequireStrictTypes : did not handle multi-directive declare statements + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3722] : Potential "Uninitialized string offset 1" in octal notation backfill + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3736] : PEAR/FunctionDeclaration: prevent fixer removing the close brace (and creating a parse error) when there is no space between the open brace and close brace of a function + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3739] : PEAR/FunctionDeclaration: prevent fixer conflict, and potentially creating a parse error, for unconventionally formatted return types + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3770] : Squiz/NonExecutableCode: prevent false positives for switching between PHP and HTML + - Thanks to [Dan Wallis][@fredden] for the patch +- Fixed bug [#3773] : Tokenizer/PHP: tokenization of the readonly keyword when used in combination with PHP 8.2 disjunctive normal types + - Thanks to [Dan Wallis][@fredden] and [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3776] : Generic/JSHint: error when JSHint is not available + - Thanks to [Dan Wallis][@fredden] for the patch +- Fixed bug [#3777] : Squiz/NonExecutableCode: slew of bug fixes, mostly related to modern PHP + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3778] : Squiz/LowercasePHPFunctions: bug fix for class names in attributes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3779] : Generic/ForbiddenFunctions: bug fix for class names in attributes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3785] : Squiz.Commenting.FunctionComment: potential "Uninitialized string offset 0" when a type contains a duplicate pipe symbol + - Thanks to [Dan Wallis][@fredden] for the patch +- Fixed bug [#3787] : PEAR/Squiz/[MultiLine]FunctionDeclaration: allow for PHP 8.1 new in initializers + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3789] : Incorrect tokenization for ternary operator with `match` inside of it + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3790] : PSR12/AnonClassDeclaration: prevent fixer creating parse error when there was no space before the open brace + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3797] : Tokenizer/PHP: more context sensitive keyword fixes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3801] : File::getMethodParameters(): allow for readonly promoted properties without visibility + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3805] : Generic/FunctionCallArgumentSpacing: prevent fixer conflict over PHP 7.3+ trailing comma's in function calls + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3806] : Squiz.PHP.InnerFunctions sniff now correctly reports inner functions declared within a closure + - Thanks to [@Daimona] for the patch +- Fixed bug [#3809] : GitBlame report was broken when passing a basepath + - Thanks to [Chris][@datengraben] for the patch +- Fixed bug [#3813] : Squiz.Commenting.FunctionComment: false positive for parameter name mismatch on parameters annotated as passed by reference + - Thanks to [Dan Wallis][@fredden] for the patch +- Fixed bug [#3833] : Generic.PHP.LowerCaseType: fixed potential undefined array index notice + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3846] : PSR2.Classes.ClassDeclaration.CloseBraceAfterBody : fixer will no longer remove indentation on the close brace line + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3854] : Fatal error when using Gitblame report in combination with `--basepath` and running from project subdirectory + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3856] : PSR12.Traits.UseDeclaration was using the wrong error code - SpacingAfterAs - for spacing issues after the `use` keyword + - These will now be reported using the SpacingAfterUse error code + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3856] : PSR12.Traits.UseDeclaration did not check spacing after `use` keyword for multi-line trait use statements + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3867] : Tokenizer/PHP: union type and intersection type operators were not correctly tokenized for static properties without explicit visibility + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3877] : Filter names can be case-sensitive. The -h help text will now display the correct case for the available filters + - Thanks to [@simonsan] for the patch +- Fixed bug [#3893] : Generic/DocComment : the SpacingAfterTagGroup fixer could accidentally remove ignore annotations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3898] : Squiz/NonExecutableCode : the sniff could get confused over comments in unexpected places + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3904] : Squiz/FunctionSpacing : prevent potential fixer conflict + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug [#3906] : Tokenizer/CSS: bug fix related to the unsupported slash comment syntax + - Thanks to [Dan Wallis][@fredden] for the patch +- Fixed bug [#3913] : Config did not always correctly store unknown "long" arguments in the `$unknown` property + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +Thanks go to [Dan Wallis][@fredden] and [Danny van der Sluijs][@DannyvdSluijs] for reviewing quite a few of the PRs for this release. +Additionally, thanks to [Alexander Turek][@derrabus] for consulting on the repo change over. + +[#2857]: https://github.com/squizlabs/PHP_CodeSniffer/issues/2857 +[#3386]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3386 +[#3557]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3557 +[#3592]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3592 +[#3715]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3715 +[#3717]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3717 +[#3720]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3720 +[#3722]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3722 +[#3736]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3736 +[#3739]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3739 +[#3770]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3770 +[#3773]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3773 +[#3776]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3776 +[#3777]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3777 +[#3778]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3778 +[#3779]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3779 +[#3785]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3785 +[#3787]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3787 +[#3789]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3789 +[#3790]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3790 +[#3797]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3797 +[#3801]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3801 +[#3805]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3805 +[#3806]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3806 +[#3809]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3809 +[#3813]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3813 +[#3833]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3833 +[#3846]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3846 +[#3854]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3854 +[#3856]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3856 +[#3867]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3867 +[#3877]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3877 +[#3893]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3893 +[#3898]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3898 +[#3904]: https://github.com/squizlabs/PHP_CodeSniffer/issues/3904 +[#3906]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3906 +[#3913]: https://github.com/squizlabs/PHP_CodeSniffer/pull/3913 + +## [3.7.2] - 2023-02-23 +### Changed +- Newer versions of Composer will now suggest installing PHPCS using require-dev instead of require + - Thanks to [Gary Jones][@GaryJones] for the patch +- A custom Out Of Memory error will now be shown if PHPCS or PHPCBF run out of memory during a run + - Error message provides actionable information about how to fix the problem and ensures the error is not silent + - Thanks to [Juliette Reinders Folmer][@jrfnl] and [Alain Schlesser][@schlessera] for the patch +- Generic.PHP.LowerCaseType sniff now correctly examines types inside arrow functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Formatting.OperatorBracket no longer reports false positives in match() structures + +### Fixed +- Fixed bug #3616 : Squiz.PHP.DisallowComparisonAssignment false positive for PHP 8 match expression + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3618 : Generic.WhiteSpace.ArbitraryParenthesesSpacing false positive for return new parent() + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3632 : Short list not tokenized correctly in control structures without braces + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3639 : Tokenizer not applying tab replacement to heredoc/nowdoc closers + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3640 : Generic.WhiteSpace.DisallowTabIndent not reporting errors for PHP 7.3 flexible heredoc/nowdoc syntax + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3645 : PHPCS can show 0 exit code when running in parallel even if child process has fatal error + - Thanks to [Alex Panshin][@enl] for the patch +- Fixed bug #3653 : False positives for match() in OperatorSpacingSniff + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #3666 : PEAR.Functions.FunctionCallSignature incorrect indent fix when checking mixed HTML/PHP files +- Fixed bug #3668 : PSR12.Classes.ClassInstantiation.MissingParentheses false positive when instantiating parent classes + - Similar issues also fixed in Generic.Functions.FunctionCallArgumentSpacing and Squiz.Formatting.OperatorBracket + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3672 : Incorrect ScopeIndent.IncorrectExact report for match inside array literal +- Fixed bug #3694 : Generic.WhiteSpace.SpreadOperatorSpacingAfter does not ignore spread operator in PHP 8.1 first class callables + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.7.1] - 2022-06-18 +### Fixed +- Fixed bug #3609 : Methods/constants with name empty/isset/unset are always reported as error + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.7.0] - 2022-06-13 +### Added +- Added support for PHP 8.1 explicit octal notation + - This new syntax has been backfilled for PHP versions less than 8.1 + - Thanks to [Mark Baker][@MarkBaker] for the patch + - Thanks to [Juliette Reinders Folmer][@jrfnl] for additional fixes +- Added support for PHP 8.1 enums + - This new syntax has been backfilled for PHP versions less than 8.1 + - Includes a new T_ENUM_CASE token to represent the case statements inside an enum + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch + - Thanks to [Juliette Reinders Folmer][@jrfnl] for additional core and sniff support +- Added support for the PHP 8.1 readonly token + - Tokenzing of the readonly keyword has been backfilled for PHP versions less than 8.1 + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Added support for PHP 8.1 intersection types + - Includes a new T_TYPE_INTERSECTION token to represent the ampersand character inside intersection types + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch + +### Changed +- File::getMethodParameters now supports the new PHP 8.1 readonly token + - When constructor property promotion is used, a new property_readonly array index is included in the return value + - This is a boolean value indicating if the property is readonly + - If the readonly token is detected, a new readonly_token array index is included in the return value + - This contains the token index of the readonly keyword + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Support for new PHP 8.1 readonly keyword has been added to the following sniffs: + - Generic.PHP.LowerCaseKeyword + - PSR2.Classes.PropertyDeclaration + - Squiz.Commenting.BlockComment + - Squiz.Commenting.DocCommentAlignment + - Squiz.Commenting.VariableComment + - Squiz.WhiteSpace.ScopeKeywordSpacing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patches +- The parallel feature is now more efficient and runs faster in some situations due to improved process management + - Thanks to [Sergei Morozov][@morozov] for the patch +- The list of installed coding standards now has consistent ordering across all platforms + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.UpperCaseConstant and Generic.PHP.LowerCaseConstant now ignore type declarations + - These sniffs now only report errors for true/false/null when used as values + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.LowerCaseType now supports the PHP 8.1 never type + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch + +### Fixed +- Fixed bug #3502 : A match statement within an array produces Squiz.Arrays.ArrayDeclaration.NoKeySpecified +- Fixed bug #3503 : Squiz.Commenting.FunctionComment.ThrowsNoFullStop false positive when one line @throw +- Fixed bug #3505 : The nullsafe operator is not counted in Generic.Metrics.CyclomaticComplexity + - Thanks to [Mark Baker][@MarkBaker] for the patch +- Fixed bug #3526 : PSR12.Properties.ConstantVisibility false positive when using public final const syntax + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3530 : Line indented incorrectly false positive when using match-expression inside switch case +- Fixed bug #3534 : Name of typed enum tokenized as T_GOTO_LABEL + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3546 : Tokenizer/PHP: bug fix - parent/static keywords in class instantiations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3550 : False positive from PSR2.ControlStructures.SwitchDeclaration.TerminatingComment when using trailing comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3575: Squiz.Scope.MethodScope misses visibility keyword on previous line + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3604: Tokenizer/PHP: bug fix for double quoted strings using ${ + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.6.2] - 2021-12-13 +### Changed +- Processing large code bases that use tab indenting inside comments and strings will now be faster + - Thanks to [Thiemo Kreuz][@thiemowmde] for the patch + +### Fixed +- Fixed bug #3388 : phpcs does not work when run from WSL drives + - Thanks to [Juliette Reinders Folmer][@jrfnl] and [Graham Wharton][@gwharton] for the patch +- Fixed bug #3422 : Squiz.WhiteSpace.ScopeClosingBrace fixer removes HTML content when fixing closing brace alignment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3437 : PSR12 does not forbid blank lines at the start of the class body + - Added new PSR12.Classes.OpeningBraceSpace sniff to enforce this +- Fixed bug #3440 : Squiz.WhiteSpace.MemberVarSpacing false positives when attributes used without docblock + - Thanks to [Vadim Borodavko][@javer] for the patch +- Fixed bug #3448 : PHP 8.1 deprecation notice while generating running time value + - Thanks to [Juliette Reinders Folmer][@jrfnl] and Andy Postnikov for the patch +- Fixed bug #3456 : PSR12.Classes.ClassInstantiation.MissingParentheses false positive using attributes on anonymous class + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3460 : Generic.Formatting.MultipleStatementAlignment false positive on closure with parameters + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3468 : do/while loops are double-counted in Generic.Metrics.CyclomaticComplexity + - Thanks to [Mark Baker][@MarkBaker] for the patch +- Fixed bug #3469 : Ternary Operator and Null Coalescing Operator are not counted in Generic.Metrics.CyclomaticComplexity + - Thanks to [Mark Baker][@MarkBaker] for the patch +- Fixed bug #3472 : PHP 8 match() expression is not counted in Generic.Metrics.CyclomaticComplexity + - Thanks to [Mark Baker][@MarkBaker] for the patch + +## [3.6.1] - 2021-10-11 +### Changed +- PHPCS annotations can now be specified using hash-style comments + - Previously, only slash-style and block-style comments could be used to do things like disable errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The new PHP 8.1 tokenisation for ampersands has been reverted to use the existing PHP_CodeSniffer method + - The PHP 8.1 tokens T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG and T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG are unsued + - Ampersands continue to be tokenized as T_BITWISE_AND for all PHP versions + - Thanks to [Juliette Reinders Folmer][@jrfnl] and [Anna Filina][@afilina] for the patch +- File::getMethodParameters() no longer incorrectly returns argument attributes in the type hint array index + - A new has_attributes array index is available and set to TRUE if the argument has attributes defined + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed an issue where some sniffs would not run on PHP files that only used the short echo tag + - The following sniffs were affected: + - Generic.Files.ExecutableFile + - Generic.Files.LowercasedFilename + - Generic.Files.LineEndings + - Generic.Files.EndFileNewline + - Generic.Files.EndFileNoNewline + - Generic.PHP.ClosingPHPTag + - Generic.PHP.Syntax + - Generic.VersionControl.GitMergeConflict + - Generic.WhiteSpace.DisallowSpaceIndent + - Generic.WhiteSpace.DisallowTabIndent + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.BlockComment now correctly applies rules for block comments after a short echo tag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Generic.NamingConventions.ConstructorName no longer throws deprecation notices on PHP 8.1 + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed false positives when using attributes in the following sniffs: + - PEAR.Commenting.FunctionComment + - Squiz.Commenting.InlineComment + - Squiz.Commenting.BlockComment + - Squiz.Commenting.VariableComment + - Squiz.WhiteSpace.MemberVarSpacing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3294 : Bug in attribute tokenization when content contains PHP end token or attribute closer on new line + - Thanks to [Alessandro Chitolina][@alekitto] for the patch + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the tests +- Fixed bug #3296 : PSR2.ControlStructures.SwitchDeclaration takes phpcs:ignore as content of case body +- Fixed bug #3297 : PSR2.ControlStructures.SwitchDeclaration.TerminatingComment does not handle try/finally blocks + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3302 : PHP 8.0 | Tokenizer/PHP: bugfix for union types using namespace operator + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3303 : findStartOfStatement() doesn't work with T_OPEN_TAG_WITH_ECHO +- Fixed bug #3316 : Arrow function not tokenized correctly when using null in union type +- Fixed bug #3317 : Problem with how phpcs handles ignored files when running in parallel + - Thanks to [Emil Andersson][@emil-nasso] for the patch +- Fixed bug #3324 : PHPCS hangs processing some nested arrow functions inside a function call +- Fixed bug #3326 : Generic.Formatting.MultipleStatementAlignment error with const DEFAULT + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3333 : Squiz.Objects.ObjectInstantiation: null coalesce operators are not recognized as assignment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3340 : Ensure interface and trait names are always tokenized as T_STRING + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3342 : PSR12/Squiz/PEAR standards all error on promoted properties with docblocks + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3345 : IF statement with no braces and double catch turned into syntax error by auto-fixer + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3352 : PSR2.ControlStructures.SwitchDeclaration can remove comments on the same line as the case statement while fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3357 : Generic.Functions.OpeningFunctionBraceBsdAllman removes return type when additional lines are present + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3362 : Generic.WhiteSpace.ScopeIndent false positive for arrow functions inside arrays +- Fixed bug #3384 : Squiz.Commenting.FileComment.SpacingAfterComment false positive on empty file +- Fixed bug #3394 : Fix PHP 8.1 auto_detect_line_endings deprecation notice +- Fixed bug #3400 : PHP 8.1: prevent deprecation notices about missing return types + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3424 : PHPCS fails when using PHP 8 Constructor property promotion with attributes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3425 : PHP 8.1 | Runner::processChildProcs(): fix passing null to non-nullable bug + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3445 : Nullable parameter after attribute incorrectly tokenized as ternary operator + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.6.0] - 2021-04-09 +### Added +- Added support for PHP 8.0 union types + - A new T_TYPE_UNION token is available to represent the pipe character + - File::getMethodParameters(), getMethodProperties(), and getMemberProperties() will now return union types + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.0 named function call arguments + - A new T_PARAM_NAME token is available to represent the label with the name of the function argument in it + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.0 attributes + - The PHP-supplied T_ATTRIBUTE token marks the start of an attribute + - A new T_ATTRIBUTE_END token is available to mark the end of an attribute + - New attribute_owner and attribute_closer indexes are available in the tokens array for all tokens inside an attribute + - Tokenizing of attributes has been backfilled for older PHP versions + - The following sniffs have been updated to support attributes: + - PEAR.Commenting.ClassComment + - PEAR.Commenting.FileComment + - PSR1.Files.SideEffects + - PSR12.Files.FileHeader + - Squiz.Commenting.ClassComment + - Squiz.Commenting.FileComment + - Squiz.WhiteSpace.FunctionSpacing + - Thanks to [Vadim Borodavko][@javer] for the patch + - Thanks to [Alessandro Chitolina][@alekitto] for the patch +- Added support for PHP 8.0 dereferencing of text strings with interpolated variables + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for PHP 8.0 match expressions + - Match expressions are now tokenised with parenthesis and scope openers and closers + - Sniffs can listen for the T_MATCH token to process match expressions + - Note that the case and default statements inside match expressions do not have scopes set + - A new T_MATCH_ARROW token is available to represent the arrows in match expressions + - A new T_MATCH_DEFAULT token is available to represent the default keyword in match expressions + - All tokenizing of match expressions has been backfilled for older PHP versions + - The following sniffs have been updated to support match expressions: + - Generic.CodeAnalysis.AssignmentInCondition + - Generic.CodeAnalysis.EmptyPHPStatement + - Thanks to [Vadim Borodavko][@javer] for the patch + - Generic.CodeAnalysis.EmptyStatement + - Generic.PHP.LowerCaseKeyword + - PEAR.ControlStructures.ControlSignature + - PSR12.ControlStructures.BooleanOperatorPlacement + - Squiz.Commenting.LongConditionClosingComment + - Squiz.Commenting.PostStatementComment + - Squiz.ControlStructures.LowercaseDeclaration + - Squiz.ControlStructures.ControlSignature + - Squiz.Formatting.OperatorBracket + - Squiz.PHP.DisallowMultipleAssignments + - Squiz.Objects.ObjectInstantiation + - Squiz.WhiteSpace.ControlStructureSpacing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added Generic.NamingConventions.AbstractClassNamePrefix to enforce that class names are prefixed with "Abstract" + - Thanks to [Anna Borzenko][@annechko] for the contribution +- Added Generic.NamingConventions.InterfaceNameSuffix to enforce that interface names are suffixed with "Interface" + - Thanks to [Anna Borzenko][@annechko] for the contribution +- Added Generic.NamingConventions.TraitNameSuffix to enforce that trait names are suffixed with "Trait" + - Thanks to [Anna Borzenko][@annechko] for the contribution + +### Changed +- The value of the T_FN_ARROW token has changed from "T_FN_ARROW" to "PHPCS_T_FN_ARROW" to avoid package conflicts + - This will have no impact on custom sniffs unless they are specifically looking at the value of the T_FN_ARROW constant + - If sniffs are just using constant to find arrow functions, they will continue to work without modification + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- File::findStartOfStatement() now works correctly when passed the last token in a statement +- File::getMethodParameters() now supports PHP 8.0 constructor property promotion + - Returned method params now include a "property_visibility" and "visibility_token" index if property promotion is detected + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- File::getMethodProperties() now includes a "return_type_end_token" index in the return value + - This indicates the last token in the return type, which is helpful when checking union types + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Include patterns are now ignored when processing STDIN + - Previously, checks using include patterns were excluded when processing STDIN when no file path was provided via --stdin-path + - Now, all include and exclude rules are ignored when no file path is provided, allowing all checks to run + - If you want include and exclude rules enforced when checking STDIN, use --stdin-path to set the file path + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Spaces are now correctly escaped in the paths to external on Windows + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.CodeAnalysis.UnusedFunctionParameter can now be configured to ignore variable usage for specific type hints + -- This allows you to suppress warnings for some variables that are not required, but leave warnings for others + -- Set the ignoreTypeHints array property to a list of type hints to ignore + -- Thanks to [Petr Bugyík][@o5] for the patch +- Generic.Formatting.MultipleStatementAlignment can now align statements at the start of the assignment token + - Previously, the sniff enforced that the values were aligned, even if this meant the assignment tokens were not + - Now, the sniff can enforce that the assignment tokens are aligned, even if this means the values are not + - Set the "alignAtEnd" sniff property to "false" to align the assignment tokens + - The default remains at "true", so the assigned values are aligned + - Thanks to [John P. Bloch][@johnpbloch] for the patch +- Generic.PHP.LowerCaseType now supports checking of typed properties + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.LowerCaseType now supports checking of union types + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Commenting.FunctionComment and Squiz.Commenting.FunctionComment sniffs can now ignore private and protected methods + - Set the "minimumVisibility" sniff property to "protected" to ignore private methods + - Set the "minimumVisibility" sniff property to "public" to ignore both private and protected methods + - The default remains at "private", so all methods are checked + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- PEAR.Commenting.FunctionComment and Squiz.Commenting.FunctionComment sniffs can now ignore return tags in any method + - Previously, only __construct and __destruct were ignored + - Set the list of method names to ignore in the "specialMethods" sniff property + - The default remains at "__construct" and "__destruct" only + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- PSR2.ControlStructures.SwitchDeclaration now supports nested switch statements where every branch terminates + - Previously, if a CASE only contained a SWITCH and no direct terminating statement, a fall-through error was displayed + - Now, the error is surpressed if every branch of the SWITCH has a terminating statement + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- The PSR2.Methods.FunctionCallSignature.SpaceBeforeCloseBracket error message is now reported on the closing parenthesis token + - Previously, the error was being reported on the function keyword, leading to confusing line numbers in the error report +- Squiz.Commenting.FunctionComment is now able to ignore function comments that are only inheritdoc statements + - Set the skipIfInheritdoc sniff property to "true" to skip checking function comments if the content is only {@inhertidoc} + - The default remains at "false", so these comments will continue to report errors + - Thanks to [Jess Myrbo][@xjm] for the patch +- Squiz.Commenting.FunctionComment now supports the PHP 8 mixed type + - Thanks to [Vadim Borodavko][@javer] for the patch +- Squiz.PHP.NonExecutableCode now has improved handling of syntax errors + - Thanks to [Thiemo Kreuz][@thiemowmde] for the patch +- Squiz.WhiteSpace.ScopeKeywordSpacing now checks spacing when using PHP 8.0 constructor property promotion + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed an issue that could occur when checking files on network drives, such as with WSL2 on Windows 10 + - This works around a long-standing PHP bug with is_readable() + - Thanks to [Michael S][@codebymikey] for the patch +- Fixed a number of false positives in the Squiz.PHP.DisallowMultipleAssignments sniff + - Sniff no longer errors for default value assignments in arrow functions + - Sniff no longer errors for assignments on first line of closure + - Sniff no longer errors for assignments after a goto label + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #2913 : Generic.WhiteSpace.ScopeIndent false positive when opening and closing tag on same line inside conditional +- Fixed bug #2992 : Enabling caching using a ruleset produces invalid cache files when using --sniffs and --exclude CLI args +- Fixed bug #3003 : Squiz.Formatting.OperatorBracket autofix incorrect when assignment used with null coalescing operator +- Fixed bug #3145 : Autoloading of sniff fails when multiple classes declared in same file +- Fixed bug #3157 : PSR2.ControlStructures.SwitchDeclaration.BreakIndent false positive when case keyword is not indented +- Fixed bug #3163 : Undefined index error with pre-commit hook using husky on PHP 7.4 + - Thanks to [Ismo Vuorinen][@ivuorinen] for the patch +- Fixed bug #3165 : Squiz.PHP.DisallowComparisonAssignment false positive when comparison inside closure +- Fixed bug #3167 : Generic.WhiteSpace.ScopeIndent false positive when using PHP 8.0 constructor property promotion +- Fixed bug #3170 : Squiz.WhiteSpace.OperatorSpacing false positive when using negation with string concat + - This also fixes the same issue in the PSR12.Operators.OperatorSpacing sniff +- Fixed bug #3177 : Incorrect tokenization of GOTO statements in mixed PHP/HTML files + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3184 : PSR2.Namespace.NamespaceDeclaration false positive on namespace operator + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3188 : Squiz.WhiteSpace.ScopeKeywordSpacing false positive for static return type + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3192 : findStartOfStatement doesn't work correctly inside switch + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Fixed bug #3195 : Generic.WhiteSpace.ScopeIndent confusing message when combination of tabs and spaces found +- Fixed bug #3197 : Squiz.NamingConventions.ValidVariableName does not use correct error code for all member vars +- Fixed bug #3219 : Generic.Formatting.MultipleStatementAlignment false positive for empty anonymous classes and closures +- Fixed bug #3258 : Squiz.Formatting.OperatorBracket duplicate error messages for unary minus + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3273 : Squiz.Functions.FunctionDeclarationArgumentSpacing reports line break as 0 spaces between parenthesis +- Fixed bug #3277 : Nullable static return typehint causes whitespace error +- Fixed bug #3284 : Unused parameter false positive when using array index in arrow function + +## [3.5.8] - 2020-10-23 +### Removed +- Reverted a change to the way include/exclude patterns are processed for STDIN content + - This change is not backwards compatible and will be re-introduced in version 3.6.0 + +## [3.5.7] - 2020-10-23 +### Added +- The PHP 8.0 T_NULLSAFE_OBJECT_OPERATOR token has been made available for older versions + - Existing sniffs that check for T_OBJECT_OPERATOR have been modified to apply the same rules for the nullsafe object operator + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The new method of PHP 8.0 tokenizing for namespaced names has been revert to thr pre 8.0 method + - This maintains backwards compatible for existing sniffs on PHP 8.0 + - This change will be removed in PHPCS 4.0 as the PHP 8.0 tokenizing method will be backported for pre 8.0 versions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for changes to the way PHP 8.0 tokenizes hash comments + - The existing PHP 5-7 behaviour has been replicated for version 8, so no sniff changes are required + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Running the unit tests now includes warnings in the found and fixable error code counts + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PSR12.Functions.NullableTypeDeclaration now supports the PHP8 static return type + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Changed +- The autoloader has been changed to fix sniff class name detection issues that may occur when running on PHP 7.4+ + - Thanks to [Eloy Lafuente][@stronk7] for the patch +- PSR12.ControlStructures.BooleanOperatorPlacement.FoundMixed error message is now more accurate when using the allowOnly setting + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch + +### Fixed +- Fixed Squiz.Formatting.OperatorBracket false positive when exiting with a negative number +- Fixed Squiz.PHP.DisallowComparisonAssignment false positive for methods called on an object +- Fixed bug #2882 : Generic.Arrays.ArrayIndent can request close brace indent to be less than the statement indent level +- Fixed bug #2883 : Generic.WhiteSpace.ScopeIndent.Incorrect issue after NOWDOC +- Fixed bug #2975 : Undefined offset in PSR12.Functions.ReturnTypeDeclaration when checking function return type inside ternary +- Fixed bug #2988 : Undefined offset in Squiz.Strings.ConcatenationSpacing during live coding + - Thanks to [Thiemo Kreuz][@thiemowmde] for the patch +- Fixed bug #2989 : Incorrect auto-fixing in Generic.ControlStructures.InlineControlStructure during live coding + - Thanks to [Thiemo Kreuz][@thiemowmde] for the patch +- Fixed bug #3007 : Directory exclude pattern improperly excludes directories with names that start the same + - Thanks to [Steve Talbot][@SteveTalbot] for the patch +- Fixed bug #3043 : Squiz.WhiteSpace.OperatorSpacing false positive for negation in arrow function + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3049 : Incorrect error with arrow function and parameter passed as reference + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3053 : PSR2 incorrect fix when multiple use statements on same line do not have whitespace between them +- Fixed bug #3058 : Progress gets unaligned when 100% happens at the end of the available dots +- Fixed bug #3059 : Squiz.Arrays.ArrayDeclaration false positive when using type casting + - Thanks to [Sergei Morozov][@morozov] for the patch +- Fixed bug #3060 : Squiz.Arrays.ArrayDeclaration false positive for static functions + - Thanks to [Sergei Morozov][@morozov] for the patch +- Fixed bug #3065 : Should not fix Squiz.Arrays.ArrayDeclaration.SpaceBeforeComma if comment between element and comma + - Thanks to [Sergei Morozov][@morozov] for the patch +- Fixed bug #3066 : No support for namespace operator used in type declarations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3075 : PSR12.ControlStructures.BooleanOperatorPlacement false positive when operator is the only content on line +- Fixed bug #3099 : Squiz.WhiteSpace.OperatorSpacing false positive when exiting with negative number + - Thanks to [Sergei Morozov][@morozov] for the patch +- Fixed bug #3102 : PSR12.Squiz.OperatorSpacing false positive for default values of arrow functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #3124 : PSR-12 not reporting error for empty lines with only whitespace +- Fixed bug #3135 : Ignore annotations are broken on PHP 8.0 + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.5.6] - 2020-08-10 +### Added +- Added support for PHP 8.0 magic constant dereferencing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added support for changes to the way PHP 8.0 tokenizes comments + - The existing PHP 5-7 behaviour has been replicated for version 8, so no sniff changes are required + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- `File::getMethodProperties()` now detects the PHP 8.0 static return type + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The PHP 8.0 static return type is now supported for arrow functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Changed +- The cache is no longer used if the list of loaded PHP extensions changes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- `Generic.NamingConventions.CamelCapsFunctionName` no longer reports `__serialize` and `__unserialize` as invalid names + - Thanks to [Filip Š][@filips123] for the patch +- `PEAR.NamingConventions.ValidFunctionName` no longer reports `__serialize` and `__unserialize` as invalid names + - Thanks to [Filip Š][@filips123] for the patch +- `Squiz.Scope.StaticThisUsage` now detects usage of `$this` inside closures and arrow functions + - Thanks to [Michał Bundyra][@michalbundyra] for the patch + +### Fixed +- Fixed bug #2877 : PEAR.Functions.FunctionCallSignature false positive for array of functions + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Fixed bug #2888 : PSR12.Files.FileHeader blank line error with multiple namespaces in one file +- Fixed bug #2926 : phpcs hangs when using arrow functions that return heredoc +- Fixed bug #2943 : Redundant semicolon added to a file when fixing PSR2.Files.ClosingTag.NotAllowed +- Fixed bug #2967 : Markdown generator does not output headings correctly + - Thanks to [Petr Bugyík][@o5] for the patch +- Fixed bug #2977 : File::isReference() does not detect return by reference for closures + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2994 : Generic.Formatting.DisallowMultipleStatements false positive for FOR loop with no body +- Fixed bug #3033 : Error generated during tokenizing of goto statements on PHP 8 + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.5.5] - 2020-04-17 +### Changed +- The T_FN backfill now works more reliably so T_FN tokens only ever represent real arrow functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed an issue where including sniffs using paths containing multiple dots would silently fail +- Generic.CodeAnalysis.EmptyPHPStatement now detects empty statements at the start of control structures + +### Fixed +- Error wording in PEAR.Functions.FunctionCallSignature now always uses "parenthesis" instead of sometimes using "bracket" + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Fixed bug #2787 : Squiz.PHP.DisallowMultipleAssignments not ignoring typed property declarations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2810 : PHPCBF fails to fix file with empty statement at start on control structure +- Fixed bug #2812 : Squiz.Arrays.ArrayDeclaration not detecting some arrays with multiple arguments on the same line + - Thanks to [Jakub Chábek][@grongor] for the patch +- Fixed bug #2826 : Generic.WhiteSpace.ArbitraryParenthesesSpacing doesn't detect issues for statements directly after a control structure + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Fixed bug #2848 : PSR12.Files.FileHeader false positive for file with mixed PHP and HTML and no file header +- Fixed bug #2849 : Generic.WhiteSpace.ScopeIndent false positive with arrow function inside array +- Fixed bug #2850 : Generic.PHP.LowerCaseKeyword complains __HALT_COMPILER is uppercase +- Fixed bug #2853 : Undefined variable error when using Info report + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2865 : Double arrow tokenized as T_STRING when placed after function named "fn" +- Fixed bug #2867 : Incorrect scope matching when arrow function used inside IF condition +- Fixed bug #2868 : phpcs:ignore annotation doesnt work inside a docblock +- Fixed bug #2878 : PSR12.Files.FileHeader conflicts with Generic.Files.LineEndings +- Fixed bug #2895 : PSR2.Methods.FunctionCallSignature.MultipleArguments false positive with arrow function argument + +## [3.5.4] - 2020-01-31 +### Changed +- The PHP 7.4 numeric separator backfill now works correctly for more float formats + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The PHP 7.4 numeric separator backfill is no longer run on PHP version 7.4.0 or greater +- File::getCondition() now accepts a 3rd argument that allows for the closest matching token to be returned + - By default, it continues to return the first matched token found from the top of the file +- Fixed detection of array return types for arrow functions +- Added Generic.PHP.DisallowRequestSuperglobal to ban the use of the $_REQUEST superglobal + - Thanks to [Jeantwan Teuma][@Morerice] for the contribution +- Generic.ControlStructures.InlineControlStructure no longer shows errors for WHILE and FOR statements without a body + - Previously it required these to have curly braces, but there were no statements to enclose in them + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PSR12.ControlStructures.BooleanOperatorPlacement can now be configured to enforce a specific operator position + - By default, the sniff ensures that operators are all at the begining or end of lines, but not a mix of both + - Set the allowOnly property to "first" to enforce all boolean operators to be at the start of a line + - Set the allowOnly property to "last" to enforce all boolean operators to be at the end of a line + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- PSR12.Files.ImportStatement now auto-fixes import statements by removing the leading slash + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Squiz.ControlStructures.ForLoopDeclaration now has a setting to ignore newline characters + - Default remains FALSE, so newlines are not allowed within FOR definitions + - Override the "ignoreNewlines" setting in a ruleset.xml file to change +- Squiz.PHP.InnerFunctions now handles multiple nested anon classes correctly + +### Fixed +- Fixed bug #2497 : Sniff properties not set when referencing a sniff using relative paths or non-native slashes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2657 : Squiz.WhiteSpace.FunctionSpacing can remove spaces between comment and first/last method during auto-fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2688 : Case statements not tokenized correctly when switch is contained within ternary +- Fixed bug #2698 : PHPCS throws errors determining auto report width when shell_exec is disabled + - Thanks to [Matthew Peveler][@MasterOdin] for the patch +- Fixed bug #2730 : PSR12.ControlStructures.ControlStructureSpacing does not ignore comments between conditions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2732 : PSR12.Files.FileHeader misidentifies file header in mixed content file +- Fixed bug #2745 : AbstractArraySniff wrong indices when mixed coalesce and ternary values + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #2748 : Wrong end of statement for fn closures + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #2751 : Autoload relative paths first to avoid confusion with files from the global include path + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #2763 : PSR12 standard reports errors for multi-line FOR definitions +- Fixed bug #2768 : Generic.Files.LineLength false positive for non-breakable strings at exactly the soft limit + - Thanks to [Alex Miles][@ghostal] for the patch +- Fixed bug #2773 : PSR2.Methods.FunctionCallSignature false positive when arrow function has array return type +- Fixed bug #2790 : PSR12.Traits.UseDeclaration ignores block comments + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Fixed bug #2791 : PSR12.Functions.NullableTypeDeclaration false positive when ternary operator used with instanceof + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2802 : Can't specify a report file path using the tilde shortcut +- Fixed bug #2804 : PHP4-style typed properties not tokenized correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2805 : Undefined Offset notice during live coding of arrow functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2843 : Tokenizer does not support alternative syntax for declare statements + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.5.3] - 2019-12-04 +### Changed +- The PHP 7.4 T_FN token has been made available for older versions + - T_FN represents the fn string used for arrow functions + - The double arrow becomes the scope opener, and uses a new T_FN_ARROW token type + - The token after the statement (normally a semicolon) becomes the scope closer + - The token is also associated with the opening and closing parenthesis of the statement + - Any functions named "fn" will cause have a T_FN token for the function name, but have no scope information + - Thanks to [Michał Bundyra][@michalbundyra] for the help with this change +- PHP 7.4 numeric separators are now tokenized in the same way when using older PHP versions + - Previously, a number like 1_000 would tokenize as T_LNUMBER (1), T_STRING (_000) + - Now, the number tokenizes as T_LNUMBER (1_000) + - Sniff developers should consider how numbers with underscores impact their custom sniffs +- The PHPCS file cache now takes file permissions into account + - The cache is now invalidated for a file when its permissions are changed +- File::getMethodParameters() now supports arrow functions +- File::getMethodProperties() now supports arrow functions +- Added Fixer::changeCodeBlockIndent() to change the indent of a code block while auto-fixing + - Can be used to either increase or decrease the indent + - Useful when moving the start position of something like a closure, where you want the content to also move +- Added Generic.Files.ExecutableFile sniff + - Ensures that files are not executable + - Thanks to [Matthew Peveler][@MasterOdin] for the contribution +- Generic.CodeAnalysis.EmptyPhpStatement now reports unnecessary semicolons after control structure closing braces + - Thanks to [Vincent Langlet][@VincentLanglet] for the patch +- Generic.PHP.LowerCaseKeyword now enforces that the "fn" keyword is lowercase + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Generic.WhiteSpace.ScopeIndent now supports static arrow functions +- PEAR.Functions.FunctionCallSignature now adjusts the indent of function argument contents during auto-fixing + - Previously, only the first line of an argument was changed, leading to inconsistent indents + - This change also applies to PSR2.Methods.FunctionCallSignature +- PSR2.ControlStructures.ControlStructureSpacing now checks whitespace before the closing parenthesis of multi-line control structures + - Previously, it incorrectly applied the whitespace check for single-line definitions only +- PSR12.Functions.ReturnTypeDeclaration now checks the return type of arrow functions + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- PSR12.Traits.UseDeclaration now ensures all trait import statements are grouped together + - Previously, the trait import section of the class ended when the first non-import statement was found + - Checking now continues throughout the class to ensure all statements are grouped together + - This also ensures that empty lines are not requested after an import statement that isn't the last one +- Squiz.Functions.LowercaseFunctionKeywords now enforces that the "fn" keyword is lowercase + - Thanks to [Michał Bundyra][@michalbundyra] for the patch + +### Fixed +- Fixed bug #2586 : Generic.WhiteSpace.ScopeIndent false positives when indenting open tags at a non tab-stop +- Fixed bug #2638 : Squiz.CSS.DuplicateClassDefinitionSniff sees comments as part of the class name + - Thanks to [Raphael Horber][@rhorber] for the patch +- Fixed bug #2640 : Squiz.WhiteSpace.OperatorSpacing false positives for some negation operators + - Thanks to [Jakub Chábek][@grongor] and [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2674 : Squiz.Functions.FunctionDeclarationArgumentSpacing prints wrong argument name in error message +- Fixed bug #2676 : PSR12.Files.FileHeader locks up when file ends with multiple inline comments +- Fixed bug #2678 : PSR12.Classes.AnonClassDeclaration incorrectly enforcing that closing brace be on a line by itself +- Fixed bug #2685 : File::getMethodParameters() setting typeHintEndToken for vars with no type hint + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2694 : AbstractArraySniff produces invalid indices when using ternary operator + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #2702 : Generic.WhiteSpace.ScopeIndent false positive when using ternary operator with short arrays + +## [3.5.2] - 2019-10-28 +### Changed +- Generic.ControlStructures.DisallowYodaConditions now returns less false positives + - False positives were being returned for array comparisions, or when performing some function calls +- Squiz.WhiteSpace.SemicolonSpacing.Incorrect error message now escapes newlines and tabs + - Provides a clearer error message as whitespace is now visible + - Also allows for better output for report types such as CSV and XML +- The error message for PSR12.Files.FileHeader.SpacingAfterBlock has been made clearer + - It now uses the wording from the published PSR-12 standard to indicate that blocks must be separated by a blank line + - Thanks to [Craig Duncan][@duncan3dc] for the patch + +### Fixed +- Fixed bug #2654 : Incorrect indentation for arguments of multiline function calls +- Fixed bug #2656 : Squiz.WhiteSpace.MemberVarSpacing removes comments before first member var during auto fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2663 : Generic.NamingConventions.ConstructorName complains about old constructor in interfaces +- Fixed bug #2664 : PSR12.Files.OpenTag incorrectly identifies PHP file with only an opening tag +- Fixed bug #2665 : PSR12.Files.ImportStatement should not apply to traits +- Fixed bug #2673 : PSR12.Traits.UseDeclaration does not allow comments or blank lines between use statements + +## [3.5.1] - 2019-10-17 +### Changed +- Very very verbose diff report output has slightly changed to improve readability + - Output is printed when running PHPCS with the --report=diff and -vvv command line arguments + - Fully qualified class names have been replaced with sniff codes + - Tokens being changed now display the line number they are on +- PSR2, PSR12, and PEAR standards now correctly check for blank lines at the start of function calls + - This check has been missing from these standards, but has now been implemented + - When using the PEAR standard, the error code is PEAR.Functions.FunctionCallSignature.FirstArgumentPosition + - When using PSR2 or PSR12, the error code is PSR2.Methods.FunctionCallSignature.FirstArgumentPosition +- PSR12.ControlStructures.BooleanOperatorPlacement no longer complains when multiple expression appears on the same line + - Previously, boolean operators were enforce to appear at the start or end of lines only + - Boolean operators can now appear in the middle of the line +- PSR12.Files.FileHeader no longer ignores comments preceding a use, namespace, or declare statement +- PSR12.Files.FileHeader now allows a hashbang line at the top of the file + +### Fixed +- Fixed bug #2506 : PSR2 standard can't auto fix multi-line function call inside a string concat statement +- Fixed bug #2530 : PEAR.Commenting.FunctionComment does not support intersection types in comments +- Fixed bug #2615 : Constant visibility false positive on non-class constants +- Fixed bug #2616 : PSR12.Files.FileHeader false positive when file only contains docblock +- Fixed bug #2619 : PSR12.Files.FileHeader locks up when inline comment is the last content in a file +- Fixed bug #2621 : PSR12.Classes.AnonClassDeclaration.CloseBraceSameLine false positive for anon class passed as function argument + - Thanks to [Martins Sipenko][@martinssipenko] for the patch +- Fixed bug #2623 : PSR12.ControlStructures.ControlStructureSpacing not ignoring indentation inside multi-line string arguments +- Fixed bug #2624 : PSR12.Traits.UseDeclaration doesnt apply the correct indent during auto fixing +- Fixed bug #2626 : PSR12.Files.FileHeader detects @var annotations as file docblocks +- Fixed bug #2628 : PSR12.Traits.UseDeclaration does not allow comments above a USE declaration +- Fixed bug #2632 : Incorrect indentation of lines starting with "static" inside closures +- Fixed bug #2641 : PSR12.Functions.NullableTypeDeclaration false positive when using new static() + +## [3.5.0] - 2019-09-27 +### Changed +- The included PSR12 standard is now complete and ready to use + - Check your code using PSR-12 by running PHPCS with --standard=PSR12 +- Added support for PHP 7.4 typed properties + - The nullable operator is now tokenized as T_NULLABLE inside property types, as it is elsewhere + - To get the type of a member var, use the File::getMemberProperties() method, which now contains a "type" array index + - This contains the type of the member var, or a blank string if not specified + - If the type is nullable, the return type will contain the leading ? + - If a type is specified, the position of the first token in the type will be set in a "type_token" array index + - If a type is specified, the position of the last token in the type will be set in a "type_end_token" array index + - If the type is nullable, a "nullable_type" array index will also be set to TRUE + - If the type contains namespace information, it will be cleaned of whitespace and comments in the return value +- The PSR1 standard now correctly bans alternate PHP tags + - Previously, it only banned short open tags and not the pre-7.0 alternate tags +- Added support for only checking files that have been locally staged in a git repo + - Use --filter=gitstaged to check these files + - You still need to give PHPCS a list of files or directories in which to apply the filter + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- JSON reports now end with a newline character +- The phpcs.xsd schema now validates phpcs-only and phpcbf-only attributes correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The tokenizer now correctly identifies inline control structures in more cases +- All helper methods inside the File class now throw RuntimeException instead of TokenizerException + - Some tokenizer methods were also throwing RuntimeExpection but now correctly throw TokenizerException + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The File::getMethodParameters() method now returns more information, and supports closure USE groups + - If a type hint is specified, the position of the last token in the hint will be set in a "type_hint_end_token" array index + - If a default is specified, the position of the first token in the default value will be set in a "default_token" array index + - If a default is specified, the position of the equals sign will be set in a "default_equal_token" array index + - If the param is not the last, the position of the comma will be set in a "comma_token" array index + - If the param is passed by reference, the position of the reference operator will be set in a "reference_token" array index + - If the param is variable length, the position of the variadic operator will be set in a "variadic_token" array index +- The T_LIST token and it's opening and closing parentheses now contain references to each other in the tokens array + - Uses the same parenthesis_opener/closer/owner indexes as other tokens + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The T_ANON_CLASS token and it's opening and closing parentheses now contain references to each other in the tokens array + - Uses the same parenthesis_opener/closer/owner indexes as other tokens + - Only applicable if the anon class is passing arguments to the constructor + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The PHP 7.4 T_BAD_CHARACTER token has been made available for older versions + - Allows you to safely look for this token, but it will not appear unless checking with PHP 7.4+ +- Metrics are now available for Squiz.WhiteSpace.FunctionSpacing + - Use the "info" report to see blank lines before/after functions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Metrics are now available for Squiz.WhiteSpace.MemberVarSpacing + - Use the "info" report to see blank lines before member vars + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added Generic.ControlStructures.DisallowYodaConditions sniff + - Ban the use of Yoda conditions + - Thanks to [Mponos George][@gmponos] for the contribution +- Added Generic.PHP.RequireStrictTypes sniff + - Enforce the use of a strict types declaration in PHP files +- Added Generic.WhiteSpace.SpreadOperatorSpacingAfter sniff + - Checks whitespace between the spread operator and the variable/function call it applies to + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added PSR12.Classes.AnonClassDeclaration sniff + - Enforces the formatting of anonymous classes +- Added PSR12.Classes.ClosingBrace sniff + - Enforces that closing braces of classes/interfaces/traits/functions are not followed by a comment or statement +- Added PSR12.ControlStructures.BooleanOperatorPlacement sniff + - Enforces that boolean operators between conditions are consistently at the start or end of the line +- Added PSR12.ControlStructures.ControlStructureSpacing sniff + - Enforces that spacing and indents are correct inside control structure parenthesis +- Added PSR12.Files.DeclareStatement sniff + - Enforces the formatting of declare statements within a file +- Added PSR12.Files.FileHeader sniff + - Enforces the order and formatting of file header blocks +- Added PSR12.Files.ImportStatement sniff + - Enforces the formatting of import statements within a file +- Added PSR12.Files.OpenTag sniff + - Enforces that the open tag is on a line by itself when used at the start of a php-only file +- Added PSR12.Functions.ReturnTypeDeclaration sniff + - Enforces the formatting of return type declarations in functions and closures +- Added PSR12.Properties.ConstantVisibility sniff + - Enforces that constants must have their visibility defined + - Uses a warning instead of an error due to this conditionally requiring the project to support PHP 7.1+ +- Added PSR12.Traits.UseDeclaration sniff + - Enforces the formatting of trait import statements within a class +- Generic.Files.LineLength ignoreComments property now ignores comments at the end of a line + - Previously, this property was incorrectly causing the sniff to ignore any line that ended with a comment + - Now, the trailing comment is not included in the line length, but the rest of the line is still checked +- Generic.Files.LineLength now only ignores unwrappable comments when the comment is on a line by itself + - Previously, a short unwrappable comment at the end of the line would have the sniff ignore the entire line +- Generic.Functions.FunctionCallArgumentSpacing no longer checks spacing around assignment operators inside function calls + - Use the Squiz.WhiteSpace.OperatorSpacing sniff to enforce spacing around assignment operators + - Note that this sniff checks spacing around all assignment operators, not just inside function calls + - The Generic.Functions.FunctionCallArgumentSpacing.NoSpaceBeforeEquals error has been removed + - use Squiz.WhiteSpace.OperatorSpacing.NoSpaceBefore instead + - The Generic.Functions.FunctionCallArgumentSpacing.NoSpaceAfterEquals error has been removed + - use Squiz.WhiteSpace.OperatorSpacing.NoSpaceAfter instead + - This also changes the PEAR/PSR2/PSR12 standards so they no longer check assignment operators inside function calls + - They were previously checking these operators when they should not have + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.ScopeIndent no longer performs exact indents checking for chained method calls + - Other sniffs can be used to enforce chained method call indent rules + - Thanks to [Pieter Frenssen][@pfrenssen] for the patch +- PEAR.WhiteSpace.ObjectOperatorIndent now supports multi-level chained statements + - When enabled, chained calls must be indented 1 level more or less than the previous line + - Set the new "multilevel" setting to TRUE in a ruleset.xml file to enable this behaviour + - Thanks to [Marcos Passos][@marcospassos] for the patch +- PSR2.ControlStructures.ControlStructureSpacing now allows whitespace after the opening parenthesis if followed by a comment + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- PSR2.Classes.PropertyDeclaration now enforces a single space after a property type keyword + - The PSR2 standard itself excludes this new check as it is not defined in the written standard + - Using the PSR12 standard will enforce this check +- Squiz.Commenting.BlockComment no longer requires blank line before comment if it's the first content after the PHP open tag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Functions.FunctionDeclarationArgumentSpacing now has more accurate error messages + - This includes renaming the SpaceAfterDefault error code to SpaceAfterEquals, which reflects the real error +- Squiz.Functions.FunctionDeclarationArgumentSpacing now checks for no space after a reference operator + - If you don't want this new behaviour, exclude the SpacingAfterReference error message in a ruleset.xml file +- Squiz.Functions.FunctionDeclarationArgumentSpacing now checks for no space after a variadic operator + - If you don't want this new behaviour, exclude the SpacingAfterVariadic error message in a ruleset.xml file +- Squiz.Functions.MultiLineFunctionDeclaration now has improved fixing for the FirstParamSpacing and UseFirstParamSpacing errors +- Squiz.Operators.IncrementDecrementUsage now suggests pre-increment of variables instead of post-increment + - This change does not enforce pre-increment over post-increment; only the suggestion has changed + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.DisallowMultipleAssignments now has a second error code for when assignments are found inside control structure conditions + - The new error code is Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure + - All other multiple assignment cases use the existing error code Squiz.PHP.DisallowMultipleAssignments.Found + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.FunctionSpacing now applies beforeFirst and afterLast spacing rules to nested functions + - Previously, these rules only applied to the first and last function in a class, interface, or trait + - These rules now apply to functions nested in any statement block, including other functions and conditions +- Squiz.WhiteSpace.OperatorSpacing now has improved handling of parse errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.OperatorSpacing now checks spacing around the instanceof operator + - Thanks to [Jakub Chábek][@grongor] for the patch +- Squiz.WhiteSpace.OperatorSpacing can now enforce a single space before assignment operators + - Previously, the sniff this spacing as multiple assignment operators are sometimes aligned + - Now, you can set the ignoreSpacingBeforeAssignments sniff property to FALSE to enable checking + - Default remains TRUE, so spacing before assignments is not checked by default + - Thanks to [Jakub Chábek][@grongor] for the patch + +### Fixed +- Fixed bug #2391 : Sniff-specific ignore rules inside rulesets are filtering out too many files + - Thanks to [Juliette Reinders Folmer][@jrfnl] and [Willington Vega][@wvega] for the patch +- Fixed bug #2478 : FunctionCommentThrowTag.WrongNumber when exception is thrown once but built conditionally +- Fixed bug #2479 : Generic.WhiteSpace.ScopeIndent error when using array destructing with exact indent checking +- Fixed bug #2498 : Squiz.Arrays.ArrayDeclaration.MultiLineNotAllowed autofix breaks heredoc +- Fixed bug #2502 : Generic.WhiteSpace.ScopeIndent false positives with nested switch indentation and case fall-through +- Fixed bug #2504 : Generic.WhiteSpace.ScopeIndent false positives with nested arrays and nowdoc string +- Fixed bug #2511 : PSR2 standard not checking if closing paren of single-line function declaration is on new line +- Fixed bug #2512 : Squiz.PHP.NonExecutableCode does not support alternate SWITCH control structure + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2522 : Text generator throws error when code sample line is too long + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2526 : XML report format has bad syntax on Windows + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2529 : Generic.Formatting.MultipleStatementAlignment wrong error for assign in string concat +- Fixed bug #2534 : Unresolvable installed_paths can lead to open_basedir errors + - Thanks to [Oliver Nowak][@ndm2] for the patch +- Fixed bug #2541 : Text doc generator does not allow for multi-line rule explanations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2549 : Searching for a phpcs.xml file can throw warnings due to open_basedir restrictions + - Thanks to [Matthew Peveler][@MasterOdin] for the patch +- Fixed bug #2558 : PHP 7.4 throwing offset syntax with curly braces is deprecated message + - Thanks to [Matthew Peveler][@MasterOdin] for the patch +- Fixed bug #2561 : PHP 7.4 compatibility fix / implode argument order + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2562 : Inline WHILE triggers SpaceBeforeSemicolon incorrectly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2565 : Generic.ControlStructures.InlineControlStructure confused by mixed short/long tags + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2566 : Author tag email validation doesn't support all TLDs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2575 : Custom error messages don't have data replaced when cache is enabled +- Fixed bug #2601 : Squiz.WhiteSpace.FunctionSpacing incorrect fix when spacing is 0 +- Fixed bug #2608 : PSR2 throws errors for use statements when multiple namespaces are defined in a file + +## [3.4.2] - 2019-04-11 +### Changed +- Squiz.Arrays.ArrayDeclaration now has improved handling of syntax errors + +### Fixed +- Fixed an issue where the PCRE JIT on PHP 7.3 caused PHPCS to die when using the parallel option + - PHPCS now disables the PCRE JIT before running +- Fixed bug #2368 : MySource.PHP.AjaxNullComparison throws error when first function has no doc comment +- Fixed bug #2414 : Indention false positive in switch/case/if combination +- Fixed bug #2423 : Squiz.Formatting.OperatorBracket.MissingBrackets error with static +- Fixed bug #2450 : Indentation false positive when closure containing nested IF conditions used as function argument +- Fixed bug #2452 : LowercasePHPFunctions sniff failing on "new \File()" +- Fixed bug #2453 : Squiz.CSS.SemicolonSpacingSniff false positive when style name proceeded by an asterisk + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2464 : Fixer conflict between Generic.WhiteSpace.ScopeIndent and Squiz.WhiteSpace.ScopeClosingBrace when class indented 1 space +- Fixed bug #2465 : Excluding a sniff by path is not working +- Fixed bug #2467 : PHP open/close tags inside CSS files are replaced with internal PHPCS token strings when auto fixing + +## [3.4.1] - 2019-03-19 +### Changed +- The PEAR installable version of PHPCS was missing some files, which have been re-included in this release + - The code report was not previously available for PEAR installs + - The Generic.Formatting.SpaceBeforeCast sniff was not previously available for PEAR installs + - The Generic.WhiteSpace.LanguageConstructSpacing sniff was not previously available for PEAR installs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PHPCS will now refuse to run if any of the required PHP extensions are not loaded + - Previously, PHPCS only relied on requirements being checked by PEAR and Composer + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Ruleset XML parsing errors are now displayed in a readable format so they are easier to correct + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The PSR2 standard no longer throws duplicate errors for spacing around FOR loop parentheses + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- T_PHPCS_SET tokens now contain sniffCode, sniffProperty, and sniffPropertyValue indexes + - Sniffs can use this information instead of having to parse the token content manually +- Added more guard code for syntax errors to various CSS sniffs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Commenting.DocComment error messages now contain the name of the comment tag that caused the error + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.ControlStructures.InlineControlStructure now handles syntax errors correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Debug.JSHint now longer requires rhino and can be run directly from the npm install + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Files.LineEndings no longer adds superfluous new line at the end of JS and CSS files + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Formatting.DisallowMultipleStatements no longer tries fix lines containing phpcs:ignore statements + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Functions.FunctionCallArgumentSpacing now has improved performance and anonymous class support + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.ScopeIndent now respects changes to the "exact" property using phpcs:set mid-way through a file + - This allows you change the "exact" rule for only some parts of a file +- Generic.WhiteSpace.ScopeIndent now disables exact indent checking inside all arrays + - Previously, this was only done when using long array syntax, but it now works for short array syntax as well +- PEAR.Classes.ClassDeclaration now has improved handling of PHPCS annotations and tab indents +- PSR12.Classes.ClassInstantiation has changed it's error code from MissingParenthesis to MissingParentheses +- PSR12.Keywords.ShortFormTypeKeywords now ignores all spacing inside type casts during both checking and fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Classes.LowercaseClassKeywords now examines the class keyword for anonymous classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.ControlStructures.ControlSignature now has improved handling of parse errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.PostStatementComment fixer no longer adds a blank line at the start of a JS file that begins with a comment + - Fixes a conflict between this sniff and the Squiz.WhiteSpace.SuperfluousWhitespace sniff + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.PostStatementComment now ignores comments inside control structure conditions, such as FOR loops + - Fixes a conflict between this sniff and the Squiz.ControlStructures.ForLoopDeclaration sniff + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.FunctionCommentThrowTag now has improved support for unknown exception types and namespaces + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.ControlStructures.ForLoopDeclaration has improved whitespace, closure, and empty expression support + - The SpacingAfterSecondNoThird error code has been removed as part of these fixes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.CSS.ClassDefinitionOpeningBraceSpace now handles comments and indentation correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.CSS.ClassDefinitionClosingBrace now handles comments, indentation, and multiple statements on the same line correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.CSS.Opacity now handles comments correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.CSS.SemicolonSpacing now handles comments and syntax errors correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.NamingConventions.ValidVariableName now supports variables inside anonymous classes correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.LowercasePHPFunctions now handles use statements, namespaces, and comments correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.FunctionSpacing now fixes function spacing correctly when a function is the first content in a file + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.SuperfluousWhitespace no longer throws errors for spacing between functions and properties in anon classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Zend.Files.ClosingTag no longer adds a semi-colon during fixing of a file that only contains a comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Zend.NamingConventions.ValidVariableName now supports variables inside anonymous classes correctly + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed bug #2298 : PSR2.Classes.ClassDeclaration allows extended class on new line + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #2337 : Generic.WhiteSpace.ScopeIndent incorrect error when multi-line function call starts on same line as open tag +- Fixed bug #2348 : Cache not invalidated when changing a ruleset included by another +- Fixed bug #2376 : Using __halt_compiler() breaks Generic.PHP.ForbiddenFunctions unless it's last in the function list + - Thanks to [Sijun Zhu][@Billz95] for the patch +- Fixed bug #2393 : The gitmodified filter will infinitely loop when encountering deleted file paths + - Thanks to [Lucas Manzke][@lmanzke] for the patch +- Fixed bug #2396 : Generic.WhiteSpace.ScopeIndent incorrect error when multi-line IF condition mixed with HTML +- Fixed bug #2431 : Use function/const not tokenized as T_STRING when preceded by comment + +## [3.4.0] - 2018-12-20 +### Deprecated +- The Generic.Formatting.NoSpaceAfterCast sniff has been deprecated and will be removed in version 4 + - The functionality of this sniff is now available in the Generic.Formatting.SpaceAfterCast sniff + - Include the Generic.Formatting.SpaceAfterCast sniff and set the "spacing" property to "0" + - As soon as possible, replace all instances of the old sniff code with the new sniff code and property setting + - The existing sniff will continue to work until version 4 has been released + +### Changed +- Rule include patterns in a ruleset.xml file are now evaluated as OR instead of AND + - Previously, a file had to match every include pattern and no exclude patterns to be included + - Now, a file must match at least one include pattern and no exclude patterns to be included + - This is a bug fix as include patterns are already documented to work this way +- New token T_BITWISE_NOT added for the bitwise not operator + - This token was previously tokenized as T_NONE + - Any sniffs specifically looking for T_NONE tokens with a tilde as the contents must now also look for T_BITWISE_NOT + - Sniffs can continue looking for T_NONE as well as T_BITWISE_NOT to support older PHP_CodeSniffer versions +- All types of binary casting are now tokenized as T_BINARY_CAST + - Previously, the 'b' in 'b"some string with $var"' would be a T_BINARY_CAST, but only when the string contained a var + - This change ensures the 'b' is always tokenized as T_BINARY_CAST + - This change also converts '(binary)' from T_STRING_CAST to T_BINARY_CAST + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the help with this patch +- Array properties set inside a ruleset.xml file can now extend a previous value instead of always overwriting it + - e.g., if you include a ruleset that defines forbidden functions, can you now add to that list instead of having to redefine it + - To use this feature, add extends="true" to the property tag + - e.g., property name="forbiddenFunctionNames" type="array" extend="true" + - Thanks to [Michael Moravec][@Majkl578] for the patch +- If $XDG_CACHE_HOME is set and points to a valid directory, it will be used for caching instead of the system temp directory +- PHPCBF now disables parallel running if you are passing content on STDIN + - Stops an error from being shown after the fixed output is printed +- The progress report now shows files with tokenizer errors as skipped (S) instead of a warning (W) + - The tokenizer error is still displayed in reports as normal + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The Squiz standard now ensures there is no space between an increment/decrement operator and its variable +- The File::getMethodProperties() method now includes a has_body array index in the return value + - FALSE if the method has no body (as with abstract and interface methods) or TRUE otherwise + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- The File::getTokensAsString() method now throws an exception if the $start param is invalid + - If the $length param is invalid, an empty string will be returned + - Stops an infinite loop when the function is passed invalid data + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added new Generic.CodeAnalysis.EmptyPHPStatement sniff + - Warns when it finds empty PHP open/close tag combinations or superfluous semicolons + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added new Generic.Formatting.SpaceBeforeCast sniff + - Ensures there is exactly 1 space before a type cast, unless the cast statement is indented or multi-line + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added new Generic.VersionControl.GitMergeConflict sniff + - Detects merge conflict artifacts left in files + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added Generic.WhiteSpace.IncrementDecrementSpacing sniff + - Ensures there is no space between the operator and the variable it applies to + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added PSR12.Functions.NullableTypeDeclaration sniff + - Ensures there is no space after the question mark in a nullable type declaration + - Thanks to [Timo Schinkel][@timoschinkel] for the contribution +- A number of sniffs have improved support for methods in anonymous classes + - These sniffs would often throw the same error twice for functions in nested classes + - Error messages have also been changed to be less confusing + - The full list of affected sniffs is: + - Generic.NamingConventions.CamelCapsFunctionName + - PEAR.NamingConventions.ValidFunctionName + - PSR1.Methods.CamelCapsMethodName + - PSR2.Methods.MethodDeclaration + - Squiz.Scope.MethodScope + - Squiz.Scope.StaticThisUsage + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.CodeAnalysis.UnusedFunctionParameter now only skips functions with empty bodies when the class implements an interface + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.CodeAnalysis.UnusedFunctionParameter now has additional error codes to indicate where unused params were found + - The new error code prefixes are: + - FoundInExtendedClass: when the class extends another + - FoundInImplementedInterface: when the class implements an interface + - Found: used in all other cases, including closures + - The new error code suffixes are: + - BeforeLastUsed: the unused param was positioned before the last used param in the function signature + - AfterLastUsed: the unused param was positioned after the last used param in the function signature + - This makes the new error code list for this sniff: + - Found + - FoundBeforeLastUsed + - FoundAfterLastUsed + - FoundInExtendedClass + - FoundInExtendedClassBeforeLastUsed + - FoundInExtendedClassAfterLastUsed + - FoundInImplementedInterface + - FoundInImplementedInterfaceBeforeLastUsed + - FoundInImplementedInterfaceAfterLastUsed + - These errors code make it easier for specific cases to be ignored or promoted using a ruleset.xml file + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Generic.Classes.DuplicateClassName now inspects traits for duplicate names as well as classes and interfaces + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Generic.Files.InlineHTML now ignores a BOM at the start of the file + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Generic.PHP.CharacterBeforePHPOpeningTag now ignores a BOM at the start of the file + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Generic.Formatting.SpaceAfterCast now has a setting to specify how many spaces are required after a type cast + - Default remains 1 + - Override the "spacing" setting in a ruleset.xml file to change + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Formatting.SpaceAfterCast now has a setting to ignore newline characters after a type cast + - Default remains FALSE, so newlines are not allowed + - Override the "ignoreNewlines" setting in a ruleset.xml file to change + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Formatting.SpaceAfterNot now has a setting to specify how many spaces are required after a NOT operator + - Default remains 1 + - Override the "spacing" setting in a ruleset.xml file to change + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Formatting.SpaceAfterNot now has a setting to ignore newline characters after the NOT operator + - Default remains FALSE, so newlines are not allowed + - Override the "ignoreNewlines" setting in a ruleset.xml file to change + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Functions.FunctionDeclaration now checks spacing before the opening parenthesis of functions with no body + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- PEAR.Functions.FunctionDeclaration now enforces no space before the semicolon in functions with no body + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- PSR2.Classes.PropertyDeclaration now checks the order of property modifier keywords + - This is a rule that is documented in PSR-2 but was not enforced by the included PSR2 standard until now + - This sniff is also able to fix the order of the modifier keywords if they are incorrect + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PSR2.Methods.MethodDeclaration now checks method declarations inside traits + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Squiz.Commenting.InlineComment now has better detection of comment block boundaries +- Squiz.Classes.ClassFileName now checks that a trait name matches the filename + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Squiz.Classes.SelfMemberReference now supports scoped declarations and anonymous classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Classes.SelfMemberReference now fixes multiple errors at once, increasing fixer performance + - Thanks to [Gabriel Ostrolucký][@ostrolucky] for the patch +- Squiz.Functions.LowercaseFunctionKeywords now checks abstract and final prefixes, and auto-fixes errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Objects.ObjectMemberComma.Missing has been renamed to Squiz.Objects.ObjectMemberComma.Found + - The error is thrown when the comma is found but not required, so the error code was incorrect + - If you are referencing the old error code in a ruleset XML file, please use the new code instead + - If you wish to maintain backwards compatibility, you can provide rules for both the old and new codes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.ObjectOperatorSpacing is now more tolerant of parse errors +- Squiz.WhiteSpace.ObjectOperatorSpacing now fixes errors more efficiently + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed bug #2109 : Generic.Functions.CallTimePassByReference false positive for bitwise and used in function argument +- Fixed bug #2165 : Conflict between Squiz.Arrays.ArrayDeclaration and ScopeIndent sniffs when heredoc used in array +- Fixed bug #2167 : Generic.WhiteSpace.ScopeIndent shows invalid error when scope opener indented inside inline HTML +- Fixed bug #2178 : Generic.NamingConventions.ConstructorName matches methods in anon classes with same name as containing class + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2190 : PEAR.Functions.FunctionCallSignature incorrect error when encountering trailing PHPCS annotation + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2194 : Generic.Whitespace.LanguageConstructSpacing should not be checking namespace operators + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2202 : Squiz.WhiteSpace.OperatorSpacing throws error for negative index when using curly braces for string access + - Same issue fixed in Squiz.Formatting.OperatorBracket + - Thanks to [Andreas Buchenrieder][@anbuc] for the patch +- Fixed bug #2210 : Generic.NamingConventions.CamelCapsFunctionName not ignoring SoapClient __getCookies() method + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2211 : PSR2.Methods.MethodDeclaration gets confused over comments between modifier keywords + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2212 : FUNCTION and CONST in use groups being tokenised as T_FUNCTION and T_CONST + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Fixed bug #2214 : File::getMemberProperties() is recognizing method params as properties + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2236 : Memory info measurement unit is Mb but probably should be MB +- Fixed bug #2246 : CSS tokenizer does not tokenize class names correctly when they contain the string NEW + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2278 : Squiz.Operators.ComparisonOperatorUsage false positive when inline IF contained in parentheses + - Thanks to [Arnout Boks][@aboks] for the patch +- Fixed bug #2284 : Squiz.Functions.FunctionDeclarationArgumentSpacing removing type hint during fixing + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #2297 : Anonymous class not tokenized correctly when used as argument to another anon class + - Thanks to [Michał Bundyra][@michalbundyra] for the patch + +## [2.9.2] - 2018-11-08 +### Changed +- PHPCS should now run under PHP 7.3 without deprecation warnings + - Thanks to [Nick Wilde][@NickDickinsonWilde] for the patch + +### Fixed +- Fixed bug #1496 : Squiz.Strings.DoubleQuoteUsage not unescaping dollar sign when fixing + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #1549 : Squiz.PHP.EmbeddedPhp fixer conflict with // comment before PHP close tag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1890 : Incorrect Squiz.WhiteSpace.ControlStructureSpacing.NoLineAfterClose error between catch and finally statements + +## [3.3.2] - 2018-09-24 +### Changed +- Fixed a problem where the report cache was not being cleared when the sniffs inside a standard were updated +- The info report (--report=info) now has improved formatting for metrics that span multiple lines + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The unit test runner now skips .bak files when looking for test cases + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The Squiz standard now ensures underscores are not used to indicate visibility of private members vars and methods + - Previously, this standard enforced the use of underscores +- Generic.PHP.NoSilencedErrors error messages now contain a code snippet to show the context of the error + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Arrays.ArrayDeclaration no longer reports errors for a comma on a line new after a here/nowdoc + - Also stops a parse error being generated when auto-fixing + - The SpaceBeforeComma error message has been changed to only have one data value instead of two +- Squiz.Commenting.FunctionComment no longer errors when trying to fix indents of multi-line param comments +- Squiz.Formatting.OperatorBracket now correctly fixes statements that contain strings +- Squiz.PHP.CommentedOutCode now ignores more @-style annotations and includes better comment block detection + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed a problem where referencing a relative file path in a ruleset XML file could add unnecessary sniff exclusions + - This didn't actually exclude anything, but caused verbose output to list strange exclusion rules +- Fixed bug #2110 : Squiz.WhiteSpace.FunctionSpacing is removing indents from the start of functions when fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2115 : Squiz.Commenting.VariableComment not checking var types when the @var line contains a comment +- Fixed bug #2120 : Tokenizer fails to match T_INLINE_ELSE when used after function call containing closure +- Fixed bug #2121 : Squiz.PHP.DisallowMultipleAssignments false positive in while loop conditions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2127 : File::findExtendedClassName() doesn't support nested classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2138 : Tokenizer detects wrong token for php ::class feature with spaces +- Fixed bug #2143 : PSR2.Namespaces.UseDeclaration does not properly fix "use function" and "use const" statements + - Thanks to [Chris Wilkinson][@thewilkybarkid] for the patch +- Fixed bug #2144 : Squiz.Arrays.ArrayDeclaration does incorrect align calculation in array with cyrillic keys +- Fixed bug #2146 : Zend.Files.ClosingTag removes closing tag from end of file without inserting a semicolon +- Fixed bug #2151 : XML schema not updated with the new array property syntax + +## [3.3.1] - 2018-07-27 +### Removed +- Support for HHVM has been dropped due to recent unfixed bugs and HHVM refocus on Hack only + - Thanks to [Walt Sorensen][@photodude] and [Juliette Reinders Folmer][@jrfnl] for helping to remove all HHVM exceptions from the core + +### Changed +- The full report (the default report) now has improved word wrapping for multi-line messages and sniff codes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The summary report now sorts files based on their directory location instead of just a basic string sort + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The source report now orders error codes by name when they have the same number of errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The junit report no longer generates validation errors with the Jenkins xUnit plugin + - Thanks to [Nikolay Geo][@nicholascus] for the patch +- Generic.Commenting.DocComment no longer generates the SpacingBeforeTags error if tags are the first content in the docblock + - The sniff will still generate a MissingShort error if there is no short comment + - This allows the MissingShort error to be suppressed in a ruleset to make short descriptions optional +- Generic.Functions.FunctionCallArgumentSpacing now properly fixes multi-line function calls with leading commas + - Previously, newlines between function arguments would be removed + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.Syntax will now use PHP_BINARY instead of trying to discover the executable path + - This ensures that the sniff will always syntax check files using the PHP version that PHPCS is running under + - Setting the php_path config var will still override this value as normal + - Thanks to [Willem Stuursma-Ruwen][@willemstuursma] for the patch +- PSR2.Namespaces.UseDeclaration now supports commas at the end of group use declarations + - Also improves checking and fixing for use statements containing parse errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Arrays.ArrayDeclaration no longer removes the array opening brace while fixing + - This could occur when the opening brace was on a new line and the first array key directly followed + - This change also stops the KeyNotAligned error message being incorrectly reported in these cases +- Squiz.Arrays.ArrayDeclaration no longer tries to change multi-line arrays to single line when they contain comments + - Fixes a conflict between this sniff and some indentation sniffs +- Squiz.Classes.ClassDeclaration no longer enforces spacing rules when a class is followed by a function + - Fixes a conflict between this sniff and the Squiz.WhiteSpace.FunctionSpacing sniff +- The Squiz.Classes.ValidClassName.NotCamelCaps message now references PascalCase instead of CamelCase + - The "CamelCase class name" metric produced by the sniff has been changed to "PascalCase class name" + - This reflects the fact that the class name check is actually a Pascal Case check and not really Camel Case + - Thanks to [Tom H Anderson][@TomHAnderson] for the patch +- Squiz.Commenting.InlineComment no longer enforces spacing rules when an inline comment is followed by a docblock + - Fixes a conflict between this sniff and the Squiz.WhiteSpace.FunctionSpacing sniff +- Squiz.WhiteSpace.OperatorSpacing no longer tries to fix operator spacing if the next content is a comment on a new line + - Fixes a conflict between this sniff and the Squiz.Commenting.PostStatementComment sniff + - Also stops PHPCS annotations from being moved to a different line, potentially changing their meaning + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.FunctionSpacing no longer checks spacing of functions at the top of an embedded PHP block + - Fixes a conflict between this sniff and the Squiz.PHP.EmbeddedPHP sniff + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.MemberVarSpacing no longer checks spacing before member vars that come directly after methods + - Fixes a conflict between this sniff and the Squiz.WhiteSpace.FunctionSpacing sniff +- Squiz.WhiteSpace.SuperfluousWhitespace now recognizes unicode whitespace at the start and end of a file + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed bug #2029 : Squiz.Scope.MemberVarScope throws fatal error when a property is found in an interface + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2047 : PSR12.Classes.ClassInstantiation false positive when instantiating class from array index +- Fixed bug #2048 : GenericFormatting.MultipleStatementAlignment false positive when assigning values inside an array +- Fixed bug #2053 : PSR12.Classes.ClassInstantiation incorrectly fix when using member vars and some variable formats +- Fixed bug #2065 : Generic.ControlStructures.InlineControlStructure fixing fails when inline control structure contains closure +- Fixed bug #2072 : Squiz.Arrays.ArrayDeclaration throws NoComma error when array value is a shorthand IF statement +- Fixed bug #2082 : File with "defined() or define()" syntax triggers PSR1.Files.SideEffects.FoundWithSymbols +- Fixed bug #2095 : PSR2.Namespaces.NamespaceDeclaration does not handle namespaces defined over multiple lines + +## [3.3.0] - 2018-06-07 +### Deprecated +- The Squiz.WhiteSpace.LanguageConstructSpacing sniff has been deprecated and will be removed in version 4 + - The sniff has been moved to the Generic standard, with a new code of Generic.WhiteSpace.LanguageConstructSpacing + - As soon as possible, replace all instances of the old sniff code with the new sniff code in your ruleset.xml files + - The existing Squiz sniff will continue to work until version 4 has been released + - The new Generic sniff now also checks many more language constructs to enforce additional spacing rules + - Thanks to [Mponos George][@gmponos] for the contribution +- The current method for setting array properties in ruleset files has been deprecated and will be removed in version 4 + - Currently, setting an array value uses the string syntax "print=>echo,create_function=>null" + - Now, individual array elements are specified using a new "element" tag with "key" and "value" attributes + - For example, element key="print" value="echo" + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- The T_ARRAY_HINT token has been deprecated and will be removed in version 4 + - The token was used to ensure array type hints were not tokenized as T_ARRAY, but no other type hints were given a special token + - Array type hints now use the standard T_STRING token instead + - Sniffs referencing this token type will continue to run without error until version 4, but will not find any T_ARRAY_HINT tokens +- The T_RETURN_TYPE token has been deprecated and will be removed in version 4 + - The token was used to ensure array/self/parent/callable return types were tokenized consistently + - For namespaced return types, only the last part of the string (the class name) was tokenized as T_RETURN_TYPE + - This was not consistent and so return types are now left using their original token types so they are not skipped by sniffs + - The exception are array return types, which are tokenized as T_STRING instead of T_ARRAY, as they are for type hints + - Sniffs referencing this token type will continue to run without error until version 4, but will not find any T_RETUTN_TYPE tokens + - To get the return type of a function, use the File::getMethodProperties() method, which now contains a "return_type" array index + - This contains the return type of the function or closer, or a blank string if not specified + - If the return type is nullable, the return type will contain the leading ? + - A nullable_return_type array index in the return value will also be set to true + - If the return type contains namespace information, it will be cleaned of whitespace and comments + - To access the original return value string, use the main tokens array + +### Added +- This release contains an incomplete version of the PSR-12 coding standard + - Errors found using this standard should be valid, but it will miss a lot of violations until it is complete + - If you'd like to test and help, you can use the standard by running PHPCS with --standard=PSR12 + +### Changed +- Config values set using --runtime-set now override any config values set in rulesets or the CodeSniffer.conf file +- You can now apply include-pattern rules to individual message codes in a ruleset like you can with exclude-pattern rules + - Previously, include-pattern rules only applied to entire sniffs + - If a message code has both include and exclude patterns, the exclude patterns will be ignored +- Using PHPCS annotations to selectively re-enable sniffs is now more flexible + - Previously, you could only re-enable a sniff/category/standard using the exact same code that was disabled + - Now, you can disable a standard and only re-enable a specific category or sniff + - Or, you can disable a specific sniff and have it re-enable when you re-enable the category or standard +- The value of array sniff properties can now be set using phpcs:set annotations + - e.g., phpcs:set Standard.Category.SniffName property[] key=>value,key2=>value2 + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- PHPCS annotations now remain as T_PHPCS_* tokens instead of reverting to comment tokens when --ignore-annotations is used + - This stops sniffs (especially commenting sniffs) from generating a large number of false errors when ignoring + - Any custom sniffs that are using the T_PHPCS_* tokens to detect annotations may need to be changed to ignore them + - Check $phpcsFile->config->annotations to see if annotations are enabled and ignore when false +- You can now use fully or partially qualified class names for custom reports instead of absolute file paths + - To support this, you must specify an autoload file in your ruleset.xml file and use it to register an autoloader + - Your autoloader will need to load your custom report class when requested + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The JSON report format now does escaping in error source codes as well as error messages + - Thanks to [Martin Vasel][@marvasDE] for the patch +- Invalid installed_paths values are now ignored instead of causing a fatal error +- Improved testability of custom rulesets by allowing the installed standards to be overridden + - Thanks to [Timo Schinkel][@timoschinkel] for the patch +- The key used for caching PHPCS runs now includes all set config values + - This fixes a problem where changing config values (e.g., via --runtime-set) used an incorrect cache file +- The "Function opening brace placement" metric has been separated into function and closure metrics in the info report + - Closures are no longer included in the "Function opening brace placement" metric + - A new "Closure opening brace placement" metric now shows information for closures +- Multi-line T_YIELD_FROM statements are now replicated properly for older PHP versions +- The PSR2 standard no longer produces 2 error messages when the AS keyword in a foreach loop is not lowercase +- Specifying a path to a non-existent dir when using the --report-[reportType]=/path/to/report CLI option no longer throws an exception + - This now prints a readable error message, as it does when using --report-file +- The File::getMethodParamaters() method now includes a type_hint_token array index in the return value + - Provides the position in the token stack of the first token in the type hint +- The File::getMethodProperties() method now includes a return_type_token array index in the return value + - Provides the position in the token stack of the first token in the return type +- The File::getTokensAsString() method can now optionally return original (non tab-replaced) content + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Removed Squiz.PHP.DisallowObEndFlush from the Squiz standard + - If you use this sniff and want to continue banning ob_end_flush(), use Generic.PHP.ForbiddenFunctions instead + - You will need to set the forbiddenFunctions property in your ruleset.xml file +- Removed Squiz.PHP.ForbiddenFunctions from the Squiz standard + - Replaced by using the forbiddenFunctions property of Generic.PHP.ForbiddenFunctions in the Squiz ruleset.xml + - Functionality of the Squiz standard remains the same, but the error codes are now different + - Previously, Squiz.PHP.ForbiddenFunctions.Found and Squiz.PHP.ForbiddenFunctions.FoundWithAlternative + - Now, Generic.PHP.ForbiddenFunctions.Found and Generic.PHP.ForbiddenFunctions.FoundWithAlternative +- Added new Generic.PHP.LowerCaseType sniff + - Ensures PHP types used for type hints, return types, and type casting are lowercase + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added new Generic.WhiteSpace.ArbitraryParenthesesSpacing sniff + - Generates an error for whitespace inside parenthesis that don't belong to a function call/declaration or control structure + - Generates a warning for any empty parenthesis found + - Allows the required spacing to be set using the spacing sniff property (default is 0) + - Allows newlines to be used by setting the ignoreNewlines sniff property (default is false) + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added new PSR12.Classes.ClassInstantiation sniff + - Ensures parenthesis are used when instantiating a new class +- Added new PSR12.Keywords.ShortFormTypeKeywords sniff + - Ensures the short form of PHP types is used when type casting +- Added new PSR12.Namespaces.CompundNamespaceDepth sniff + - Ensures compound namespace use statements have a max depth of 2 levels + - The max depth can be changed by setting the 'maxDepth' sniff property in a ruleset.xml file +- Added new PSR12.Operators.OperatorSpacing sniff + - Ensures operators are preceded and followed by at least 1 space +- Improved core support for grouped property declarations + - Also improves support in Squiz.WhiteSpace.ScopeKeywordSpacing and Squiz.WhiteSpace.MemberVarSpacing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Commenting.DocComment now produces a NonParamGroup error when tags are mixed in with the @param tag group + - It would previously throw either a NonParamGroup or ParamGroup error depending on the order of tags + - This change allows the NonParamGroup error to be suppressed in a ruleset to allow the @param group to contain other tags + - Thanks to [Phil Davis][@phil-davis] for the patch +- Generic.Commenting.DocComment now continues checks param tags even if the doc comment short description is missing + - This change allows the MissingShort error to be suppressed in a ruleset without all other errors being suppressed as well + - Thanks to [Phil Davis][@phil-davis] for the patch +- Generic.CodeAnalysis.AssignmentInCondition now reports a different error code for assignments found in WHILE conditions + - The return value of a function call is often assigned in a WHILE condition, so this change makes it easier to exclude these cases + - The new code for this error message is Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition + - The error code for all other cases remains as Generic.CodeAnalysis.AssignmentInCondition.Found + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Functions.OpeningFunctionBraceBsdAllman now longer leaves trailing whitespace when moving the opening brace during fixing + - Also applies to fixes made by PEAR.Functions.FunctionDeclaration and Squiz.Functions.MultiLineFunctionDeclaration +- Generic.WhiteSpace.ScopeIndent now does a better job of fixing the indent of multi-line comments +- Generic.WhiteSpace.ScopeIndent now does a better job of fixing the indent of PHP open and close tags +- PEAR.Commenting.FunctionComment now report a different error code for param comment lines with too much padding + - Previously, any lines of a param comment that don't start at the exact comment position got the same error code + - Now, only comment lines with too little padding use ParamCommentAlignment as they are clearly mistakes + - Comment lines with too much padding may be using precision alignment as now use ParamCommentAlignmentExceeded + - This allows for excessive padding to be excluded from a ruleset while continuing to enforce a minimum padding +- PEAR.WhiteSpace.ObjectOperatorIndent now checks the indent of more chained operators + - Previously, it only checked chains beginning with a variable + - Now, it checks chains beginning with function calls, static class names, etc +- Squiz.Arrays.ArrayDeclaration now continues checking array formatting even if the key indent is not correct + - Allows for using different array indent rules while still checking/fixing double arrow and value alignment +- Squiz.Commenting.BlockComment has improved support for tab-indented comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.BlockComment auto fixing no longer breaks when two block comments follow each other + - Also stopped single-line block comments from being auto fixed when they are embedded in other code + - Also fixed as issue found when PHPCS annotations were used inside a block comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.BlockComment.LastLineIndent is now able to be fixed with phpcbf + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.BlockComment now aligns star-prefixed lines under the opening tag while fixing, instead of indenting them + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.FunctionComment.IncorrectTypeHint message no longer contains cut-off suggested type hints +- Squiz.Commenting.InlineComment now uses a new error code for inline comments at the end of a function + - Previously, all inline comments followed by a blank line threw a Squiz.Commenting.InlineComment.SpacingAfter error + - Now, inline comments at the end of a function will instead throw Squiz.Commenting.InlineComment.SpacingAfterAtFunctionEnd + - If you previously excluded SpacingAfter, add an exclusion for SpacingAfterAtFunctionEnd to your ruleset as well + - If you previously only included SpacingAfter, consider including SpacingAfterAtFunctionEnd as well + - The Squiz standard now excludes SpacingAfterAtFunctionEnd as the blank line is checked elsewhere + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.ControlStructures.ControlSignature now errors when a comment follows the closing brace of an earlier body + - Applies to catch, finally, else, elseif, and do/while structures + - The included PSR2 standard now enforces this rule + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Formatting.OperatorBracket.MissingBrackets message has been changed to remove the word "arithmetic" + - The sniff checks more than just arithmetic operators, so the message is now clearer +- Sniffs.Operators.ComparisonOperatorUsage now detects more cases of implicit true comparisons + - It could previously be confused by comparisons used as function arguments +- Squiz.PHP.CommentedOutCode now ignores simple @-style annotation comments so they are not flagged as commented out code + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.CommentedOutCode now ignores a greater number of short comments so they are not flagged as commented out code + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.DisallowComparisonAssignment no longer errors when using the null coalescing operator + - Given this operator is used almost exclusively to assign values, it didn't make sense to generate an error +- Squiz.WhiteSpacing.FunctionSpacing now has a property to specify how many blank lines should be before the first class method + - Only applies when a method is the first code block in a class (i.e., there are no member vars before it) + - Override the 'spacingBeforeFirst' property in a ruleset.xml file to change + - If not set, the sniff will use whatever value is set for the existing 'spacing' property +- Squiz.WhiteSpacing.FunctionSpacing now has a property to specify how many blank lines should be after the last class method + - Only applies when a method is the last code block in a class (i.e., there are no member vars after it) + - Override the 'spacingAfterLast' property in a ruleset.xml file to change + - If not set, the sniff will use whatever value is set for the existing 'spacing' property + +### Fixed +- Fixed bug #1863 : File::findEndOfStatement() not working when passed a scope opener +- Fixed bug #1876 : PSR2.Namespaces.UseDeclaration not giving error for use statements before the namespace declaration + - Adds a new PSR2.Namespaces.UseDeclaration.UseBeforeNamespace error message +- Fixed bug #1881 : Generic.Arrays.ArrayIndent is indenting sub-arrays incorrectly when comma not used after the last value +- Fixed bug #1882 : Conditional with missing braces confused by indirect variables +- Fixed bug #1915 : JS tokenizer fails to tokenize regular expression proceeded by boolean not operator +- Fixed bug #1920 : Directory exclude pattern improperly excludes files with names that start the same + - Thanks to [Jeff Puckett][@jpuck] for the patch +- Fixed bug #1922 : Equal sign alignment check broken when list syntax used before assignment operator +- Fixed bug #1925 : Generic.Formatting.MultipleStatementAlignment skipping assignments within closures +- Fixed bug #1931 : Generic opening brace placement sniffs do not correctly support function return types +- Fixed bug #1932 : Generic.ControlStructures.InlineControlStructure fixer moves new PHPCS annotations +- Fixed bug #1938 : Generic opening brace placement sniffs incorrectly move PHPCS annotations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1939 : phpcs:set annotations do not cause the line they are on to be ignored + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1949 : Squiz.PHP.DisallowMultipleAssignments false positive when using namespaces with static assignments +- Fixed bug #1959 : SquizMultiLineFunctionDeclaration error when param has trailing comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1963 : Squiz.Scope.MemberVarScope does not work for multiline member declaration + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1971 : Short array list syntax not correctly tokenized if short array is the first content in a file +- Fixed bug #1979 : Tokenizer does not change heredoc to nowdoc token if the start tag contains spaces +- Fixed bug #1982 : Squiz.Arrays.ArrayDeclaration fixer sometimes puts a comma in front of the last array value +- Fixed bug #1993 : PSR1/PSR2 not reporting or fixing short open tags +- Fixed bug #1996 : Custom report paths don't work on case-sensitive filesystems +- Fixed bug #2006 : Squiz.Functions.FunctionDeclarationArgumentSpacing fixer removes comment between parens when no args + - The SpacingAfterOpenHint error message has been removed + - It is replaced by the the existing SpacingAfterOpen message + - The error message format for the SpacingAfterOpen and SpacingBeforeClose messages has been changed + - These used to contain 3 pieces of data, but now only contain 2 + - If you have customised the error messages of this sniff, please review your ruleset after upgrading +- Fixed bug #2018 : Generic.Formatting.MultipleStatementAlignment does see PHP close tag as end of statement block + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #2027 : PEAR.NamingConventions.ValidFunctionName error when function name includes double underscore + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.2.3] - 2018-02-21 +### Changed +- The new phpcs: comment syntax can now be prefixed with an at symbol ( @phpcs: ) + - This restores the behaviour of the previous syntax where these comments are ignored by doc generators +- The current PHP version ID is now used to generate cache files + - This ensures that only cache files generated by the current PHP version are selected + - This change fixes caching issues when using sniffs that produce errors based on the current PHP version +- A new Tokens::$phpcsCommentTokens array is now available for sniff developers to detect phpcs: comment syntax + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The PEAR.Commenting.FunctionComment.Missing error message now includes the name of the function + - Thanks to [Yorman Arias][@cixtor] for the patch +- The PEAR.Commenting.ClassComment.Missing and Squiz.Commenting.ClassComment.Missing error messages now include the name of the class + - Thanks to [Yorman Arias][@cixtor] for the patch +- PEAR.Functions.FunctionCallSignature now only forces alignment at a specific tab stop while fixing + - It was enforcing this during checking, but this meant invalid errors if the OpeningIndent message was being muted + - This fixes incorrect errors when using the PSR2 standard with some code blocks +- Generic.Files.LineLength now ignores lines that only contain phpcs: annotation comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Formatting.MultipleStatementAlignment now skips over arrays containing comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.Syntax now forces display_errors to ON when linting + - Thanks to [Raúl Arellano][@raul338] for the patch +- PSR2.Namespaces.UseDeclaration has improved syntax error handling and closure detection + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.CommentedOutCode now has improved comment block detection for improved accuracy + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.NonExecutableCode could fatal error while fixing file with syntax error +- Squiz.PHP.NonExecutableCode now detects unreachable code after a goto statement + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.LanguageConstructSpacing has improved syntax error handling while fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Improved phpcs: annotation syntax handling for a number of sniffs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Improved auto-fixing of files with incomplete comment blocks for various commenting sniffs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed test suite compatibility with PHPUnit 7 +- Fixed bug #1793 : PSR2 forcing exact indent for function call opening statements +- Fixed bug #1803 : Squiz.WhiteSpace.ScopeKeywordSpacing removes member var name while fixing if no space after scope keyword +- Fixed bug #1817 : Blank line not enforced after control structure if comment on same line as closing brace +- Fixed bug #1827 : A phpcs:enable comment is not tokenized correctly if it is outside a phpcs:disable block + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1828 : Squiz.WhiteSpace.SuperfluousWhiteSpace ignoreBlankLines property ignores whitespace after single line comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1840 : When a comment has too many asterisks, phpcbf gives FAILED TO FIX error +- Fixed bug #1867 : Cant use phpcs:ignore where the next line is HTML +- Fixed bug #1870 : Invalid warning in multiple assignments alignment with closure or anon class +- Fixed bug #1890 : Incorrect Squiz.WhiteSpace.ControlStructureSpacing.NoLineAfterClose error between catch and finally statements +- Fixed bug #1891 : Comment on last USE statement causes false positive for PSR2.Namespaces.UseDeclaration.SpaceAfterLastUse + - Thanks to [Matt Coleman][@iammattcoleman], [Daniel Hensby][@dhensby], and [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1901 : Fixed PHPCS annotations in multi-line tab-indented comments + not ignoring whole line for phpcs:set + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.2.2] - 2017-12-20 +### Changed +- Disabled STDIN detection on Windows + - This fixes a problem with IDE plugins (e.g., PHPStorm) hanging on Windows + +## [3.2.1] - 2017-12-18 +### Changed +- Empty diffs are no longer followed by a newline character (request #1781) +- Generic.Functions.OpeningFunctionBraceKernighanRitchie no longer complains when the open brace is followed by a close tag + - This makes the sniff more useful when used in templates + - Thanks to [Joseph Zidell][@josephzidell] for the patch + +### Fixed +- Fixed problems with some scripts and plugins waiting for STDIN + - This was a notable problem with IDE plugins (e.g., PHPStorm) and build systems +- Fixed bug #1782 : Incorrect detection of operator in ternary + anonymous function + +## [3.2.0] - 2017-12-13 +### Deprecated +- This release deprecates the @codingStandards comment syntax used for sending commands to PHP_CodeSniffer + - The existing syntax will continue to work in all version 3 releases, but will be removed in version 4 + - The comment formats have been replaced by a shorter syntax: + - @codingStandardsIgnoreFile becomes phpcs:ignoreFile + - @codingStandardsIgnoreStart becomes phpcs:disable + - @codingStandardsIgnoreEnd becomes phpcs:enable + - @codingStandardsIgnoreLine becomes phpcs:ignore + - @codingStandardsChangeSetting becomes phpcs:set + - The new syntax allows for additional developer comments to be added after a -- separator + - This is useful for describing why a code block is being ignored, or why a setting is being changed + - E.g., phpcs:disable -- This code block must be left as-is. + - Comments using the new syntax are assigned new comment token types to allow them to be detected: + - phpcs:ignoreFile has the token T_PHPCS_IGNORE_FILE + - phpcs:disable has the token T_PHPCS_DISABLE + - phpcs:enable has the token T_PHPCS_ENABLE + - phpcs:ignore has the token T_PHPCS_IGNORE + - phpcs:set has the token T_PHPCS_SET + +### Changed +- The phpcs:disable and phpcs:ignore comments can now selectively ignore specific sniffs (request #604) + - E.g., phpcs:disable Generic.Commenting.Todo.Found for a specific message + - E.g., phpcs:disable Generic.Commenting.Todo for a whole sniff + - E.g., phpcs:disable Generic.Commenting for a whole category of sniffs + - E.g., phpcs:disable Generic for a whole standard + - Multiple sniff codes can be specified by comma separating them + - E.g., phpcs:disable Generic.Commenting.Todo,PSR1.Files +- @codingStandardsIgnoreLine comments now only ignore the following line if they are on a line by themselves + - If they are at the end of an existing line, they will only ignore the line they are on + - Stops some lines from accidentally being ignored + - Same rule applies for the new phpcs:ignore comment syntax +- PSR1.Files.SideEffects now respects the new phpcs:disable comment syntax + - The sniff will no longer check any code that is between phpcs:disable and phpcs:enable comments + - The sniff does not support phpcs:ignore; you must wrap code structures with disable/enable comments + - Previously, there was no way to have this sniff ignore parts of a file +- Fixed a problem where PHPCS would sometimes hang waiting for STDIN, or read incomplete versions of large files + - Thanks to [Arne Jørgensen][@arnested] for the patch +- Array properties specified in ruleset files now have their keys and values trimmed + - This saves having to do this in individual sniffs and stops errors introduced by whitespace in rulesets + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added phpcs.xsd to allow validation of ruleset XML files + - Thanks to [Renaat De Muynck][@renaatdemuynck] for the contribution +- File paths specified using --stdin-path can now point to fake file locations (request #1488) + - Previously, STDIN files using fake file paths were excluded from checking +- Setting an empty basepath (--basepath=) on the CLI will now clear a basepath set directly in a ruleset + - Thanks to [Xaver Loppenstedt][@xalopp] for the patch +- Ignore patterns are now checked on symlink target paths instead of symlink source paths + - Restores previous behaviour of this feature +- Metrics were being double counted when multiple sniffs were recording the same metric +- Added support for bash process substitution + - Thanks to [Scott Dutton][@exussum12] for the contribution +- Files included in the cache file code hash are now sorted to aid in cache file reuse across servers +- Windows BAT files can now be used outside a PEAR install + - You must have the path to PHP set in your PATH environment variable + - Thanks to [Joris Debonnet][@JorisDebonnet] for the patch +- The JS unsigned right shift assignment operator is now properly classified as an assignment operator + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The AbstractVariableSniff abstract sniff now supports anonymous classes and nested functions + - Also fixes an issue with Squiz.Scope.MemberVarScope where member vars of anonymous classes were not being checked +- Added AbstractArraySniff to make it easier to create sniffs that check array formatting + - Allows for checking of single and multi line arrays easily + - Provides a parsed structure of the array including positions of keys, values, and double arrows +- Added Generic.Arrays.ArrayIndent to enforce a single tab stop indent for array keys in multi-line arrays + - Also ensures the close brace is on a new line and indented to the same level as the original statement + - Allows for the indent size to be set using an "indent" property of the sniff +- Added Generic.PHP.DiscourageGoto to warn about the use of the GOTO language construct + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Generic.Debug.ClosureLinter was not running the gjslint command + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Generic.WhiteSpace.DisallowSpaceIndent now fixes space indents in multi-line block comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.DisallowSpaceIndent now fixes mixed space/tab indents more accurately + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.DisallowTabIndent now fixes tab indents in multi-line block comments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Functions.FunctionDeclaration no longer errors when a function declaration is the first content in a JS file + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Functions.FunctionCallSignature now requires the function name to be indented to an exact tab stop + - If the function name is not the start of the statement, the opening statement must be indented correctly instead + - Added a new fixable error code PEAR.Functions.FunctionCallSignature.OpeningIndent for this error +- Squiz.Functions.FunctionDeclarationArgumentSpacing is no longer confused about comments in function declarations + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.PHP.NonExecutableCode error messages now indicate which line the code block ending is on + - Makes it easier to identify where the code block exited or returned + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.FunctionComment now supports nullable type hints +- Squiz.Commenting.FunctionCommentThrowTag no longer assigns throw tags inside anon classes to the enclosing function +- Squiz.WhiteSpace.SemicolonSpacing now ignores semicolons used for empty statements inside FOR conditions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.ControlStructures.ControlSignature now allows configuring the number of spaces before the colon in alternative syntax + - Override the 'requiredSpacesBeforeColon' setting in a ruleset.xml file to change + - Default remains at 1 + - Thanks to [Nikola Kovacs][@nkovacs] for the patch +- The Squiz standard now ensures array keys are indented 4 spaces from the main statement + - Previously, this standard aligned keys 1 space from the start of the array keyword +- The Squiz standard now ensures array end braces are aligned with the main statement + - Previously, this standard aligned the close brace with the start of the array keyword +- The standard for PHP_CodeSniffer itself now enforces short array syntax +- The standard for PHP_CodeSniffer itself now uses the Generic.Arrays/ArrayIndent sniff rules +- Improved fixer conflicts and syntax error handling for a number of sniffs + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed bug #1462 : Error processing cyrillic strings in Tokenizer +- Fixed bug #1573 : Squiz.WhiteSpace.LanguageConstructSpacing does not properly check for tabs and newlines + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #1590 : InlineControlStructure CBF issue while adding braces to an if thats returning a nested function +- Fixed bug #1718 : Unclosed strings at EOF sometimes tokenized as T_WHITESPACE by the JS tokenizer +- Fixed bug #1731 : Directory exclusions do not work as expected when a single file name is passed to phpcs +- Fixed bug #1737 : Squiz.CSS.EmptyStyleDefinition sees comment as style definition and fails to report error +- Fixed bug #1746 : Very large reports can sometimes become garbled when using the parallel option +- Fixed bug #1747 : Squiz.Scope.StaticThisUsage incorrectly looking inside closures +- Fixed bug #1757 : Unknown type hint "object" in Squiz.Commenting.FunctionComment +- Fixed bug #1758 : PHPCS gets stuck creating file list when processing circular symlinks +- Fixed bug #1761 : Generic.WhiteSpace.ScopeIndent error on multi-line function call with static closure argument +- Fixed bug #1762 : Generic.WhiteSpace.Disallow[Space/Tab]Indent not inspecting content before open tag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1769 : Custom "define" function triggers a warning about declaring new symbols +- Fixed bug #1776 : Squiz.Scope.StaticThisUsage incorrectly looking inside anon classes +- Fixed bug #1777 : Generic.WhiteSpace.ScopeIndent incorrect indent errors when self called function proceeded by comment + +## [3.1.1] - 2017-10-17 +### Changed +- Restored preference of non-dist files over dist files for phpcs.xml and phpcs.xml.dist + - The order that the files are searched is now: .phpcs.xml, phpcs.xml, .phpcs.xml.dist, phpcs.xml.dist + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Progress output now correctly shows skipped files +- Progress output now shows 100% when the file list has finished processing (request #1697) +- Stopped some IDEs complaining about testing class aliases + - Thanks to [Vytautas Stankus][@svycka] for the patch +- Squiz.Commenting.InlineComment incorrectly identified comment blocks in some cases, muting some errors + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +### Fixed +- Fixed bug #1512 : PEAR.Functions.FunctionCallSignature enforces spaces when no arguments if required spaces is not 0 +- Fixed bug #1522 : Squiz Arrays.ArrayDeclaration and Strings.ConcatenationSpacing fixers causing parse errors with here/ nowdocs +- Fixed bug #1570 : Squiz.Arrays.ArrayDeclaration fixer removes comments between array keyword and open parentheses +- Fixed bug #1604 : File::isReference has problems with some bitwise operators and class property references + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1645 : Squiz.Commenting.InlineComment will fail to fix comments at the end of the file + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1656 : Using the --sniffs argument has a problem with case sensitivity +- Fixed bug #1657 : Uninitialized string offset: 0 when sniffing CSS +- Fixed bug #1669 : Temporary expression proceeded by curly brace is detected as function call +- Fixed bug #1681 : Huge arrays are super slow to scan with Squiz.Arrays.ArrayDeclaration sniff +- Fixed bug #1694 : Squiz.Arrays.ArrayBracketSpacing is removing some comments during fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1702 : Generic.WhiteSpaceDisallowSpaceIndent fixer bug when line only contains superfluous whitespace + +## [3.1.0] - 2017-09-20 +### Changed +- This release includes a change to support newer versions of PHPUnit (versions 4, 5, and 6 are now supported) + - The custom PHP_CodeSniffer test runner now requires a bootstrap file + - Developers with custom standards using the PHP_CodeSniffer test runner will need to do one of the following: + - run your unit tests from the PHP_CodeSniffer root dir so the bootstrap file is included + - specify the PHP_CodeSniffer bootstrap file on the command line: phpunit --bootstrap=/path/to/phpcs/tests/bootstrap.php + - require the PHP_CodeSniffer bootstrap file from your own bootstrap file + - If you don't run PHP_CodeSniffer unit tests, this change will not affect you + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- A phpcs.xml or phpcs.xml.dist file now takes precedence over the default_standard config setting + - Thanks to [Björn Fischer][@Fischer-Bjoern] for the patch +- Both phpcs.xml and phpcs.xml.dist files can now be prefixed with a dot (request #1566) + - The order that the files are searched is: .phpcs.xml, .phpcs.xml.dist, phpcs.xml, phpcs.xml.dist +- The autoloader will now search for files during unit tests runs from the same locations as during normal phpcs runs + - Allows for easier unit testing of custom standards that use helper classes or custom namespaces +- Include patterns for sniffs now use OR logic instead of AND logic + - Previously, a file had to be in each of the include patterns to be processed by a sniff + - Now, a file has to only be in at least one of the patterns + - This change reflects the original intention of the feature +- PHPCS will now follow symlinks under the list of checked directories + - This previously only worked if you specified the path to a symlink on the command line +- Output from --config-show, --config-set, and --config-delete now includes the path to the loaded config file +- PHPCS now cleanly exits if its config file is not readable + - Previously, a combination of PHP notices and PHPCS errors would be generated +- Comment tokens that start with /** are now always tokenized as docblocks + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- The PHP-supplied T_YIELD and T_YIELD_FROM token have been replicated for older PHP versions + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Added new Generic.CodeAnalysis.AssignmentInCondition sniff to warn about variable assignments inside conditions + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the contribution +- Added Generic.Files.OneObjectStructurePerFile sniff to ensure there is a single class/interface/trait per file + - Thanks to [Mponos George][@gmponos] for the contribution +- Function call sniffs now check variable function names and self/static object creation + - Specific sniffs are Generic.Functions.FunctionCallArgumentSpacing, PEAR.Functions.FunctionCallSignature, and PSR2.Methods.FunctionCallSignature + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Generic.Files.LineLength can now be configured to ignore all comment lines, no matter their length + - Set the ignoreComments property to TRUE (default is FALSE) in your ruleset.xml file to enable this + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.LowerCaseKeyword now checks self, parent, yield, yield from, and closure (function) keywords + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- PEAR.Functions.FunctionDeclaration now removes a blank line if it creates one by moving the curly brace during fixing +- Squiz.Commenting.FunctionCommentThrowTag now supports PHP 7.1 multi catch exceptions +- Squiz.Formatting.OperatorBracket no longer throws errors for PHP 7.1 multi catch exceptions +- Squiz.Commenting.LongConditionClosingComment now supports finally statements +- Squiz.Formatting.OperatorBracket now correctly fixes pipe separated flags +- Squiz.Formatting.OperatorBracket now correctly fixes statements containing short array syntax +- Squiz.PHP.EmbeddedPhp now properly fixes cases where the only content in an embedded PHP block is a comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.ControlStructureSpacing now ignores comments when checking blank lines at the top of control structures +- Squiz.WhiteSpace.ObjectOperatorSpacing now detects and fixes spaces around double colons + - Thanks to [Julius Šmatavičius][@bondas83] for the patch +- Squiz.WhiteSpace.MemberVarSpacing can now be configured to check any number of blank lines between member vars + - Set the spacing property (default is 1) in your ruleset.xml file to set the spacing +- Squiz.WhiteSpace.MemberVarSpacing can now be configured to check a different number of blank lines before the first member var + - Set the spacingBeforeFirst property (default is 1) in your ruleset.xml file to set the spacing +- Added a new PHP_CodeSniffer\Util\Tokens::$ooScopeTokens static member var for quickly checking object scope + - Includes T_CLASS, T_ANON_CLASS, T_INTERFACE, and T_TRAIT + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PHP_CodeSniffer\Files\File::findExtendedClassName() now supports extended interfaces + - Thanks to [Martin Hujer][@mhujer] for the patch + +### Fixed +- Fixed bug #1550 : Squiz.Commenting.FunctionComment false positive when function contains closure +- Fixed bug #1577 : Generic.InlineControlStructureSniff breaks with a comment between body and condition in do while loops +- Fixed bug #1581 : Sniffs not loaded when one-standard directories are being registered in installed_paths +- Fixed bug #1591 : Autoloader failing to load arbitrary files when installed_paths only set via a custom ruleset +- Fixed bug #1605 : Squiz.WhiteSpace.OperatorSpacing false positive on unary minus after comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1615 : Uncaught RuntimeException when phpcbf fails to fix files +- Fixed bug #1637 : Generic.WhiteSpaceScopeIndent closure argument indenting incorrect with multi-line strings +- Fixed bug #1638 : Squiz.WhiteSpace.ScopeClosingBrace closure argument indenting incorrect with multi-line strings +- Fixed bug #1640 : Squiz.Strings.DoubleQuoteUsage replaces tabs with spaces when fixing + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.0.2] - 2017-07-18 +### Changed +- The code report now gracefully handles tokenizer exceptions +- The phpcs and phpcbf scripts and now the only places that exit() in the code + - This allows for easier usage of core PHPCS functions from external scripts + - If you are calling Runner::runPHPCS() or Runner::runPHPCBF() directly, you will get back the full range of exit codes + - If not, catch the new DeepExitException to get the error message ($e->getMessage()) and exit code ($e->getCode()); +- NOWDOC tokens are now considered conditions, just as HEREDOC tokens are + - This makes it easier to find the start and end of a NOWDOC from any token within it + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Custom autoloaders are now only included once in case multiple standards are using the same one + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Improved tokenizing of fallthrough CASE and DEFAULT statements that share a closing statement and use curly braces +- Improved the error message when Squiz.ControlStructures.ControlSignature detects a newline after the closing parenthesis + +### Fixed +- Fixed a problem where the source report was not printing the correct number of errors found +- Fixed a problem where the --cache=/path/to/cachefile CLI argument was not working +- Fixed bug #1465 : Generic.WhiteSpace.ScopeIndent reports incorrect errors when indenting double arrows in short arrays +- Fixed bug #1478 : Indentation in fallthrough CASE that contains a closure +- Fixed bug #1497 : Fatal error if composer prepend-autoloader is set to false + - Thanks to [Kunal Mehta][@legoktm] for the patch +- Fixed bug #1503 : Alternative control structure syntax not always recognized as scoped +- Fixed bug #1523 : Fatal error when using the --suffix argument + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1526 : Use of basepath setting can stop PHPCBF being able to write fixed files +- Fixed bug #1530 : Generic.WhiteSpace.ScopeIndent can increase indent too much for lines within code blocks +- Fixed bug #1547 : Wrong token type for backslash in use function + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #1549 : Squiz.PHP.EmbeddedPhp fixer conflict with // comment before PHP close tag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1560 : Squiz.Commenting.FunctionComment fatal error when fixing additional param comment lines that have no indent + +## [3.0.1] - 2017-06-14 +### Security +- This release contains a fix for a security advisory related to the improper handling of a shell command + - A properly crafted filename would allow for arbitrary code execution when using the --filter=gitmodified command line option + - All version 3 users are encouraged to upgrade to this version, especially if you are checking 3rd-party code + - e.g., you run PHPCS over libraries that you did not write + - e.g., you provide a web service that runs PHPCS over user-uploaded files or 3rd-party repositories + - e.g., you allow external tool paths to be set by user-defined values + - If you are unable to upgrade but you check 3rd-party code, ensure you are not using the Git modified filter + - This advisory does not affect PHP_CodeSniffer version 2. + - Thanks to [Sergei Morozov][@morozov] for the report and patch + +### Changed +- Arguments on the command line now override or merge with those specified in a ruleset.xml file in all cases +- PHPCS now stops looking for a phpcs.xml file as soon as one is found, favoring the closest one to the current dir +- Added missing help text for the --stdin-path CLI option to --help +- Re-added missing help text for the --file-list and --bootstrap CLI options to --help +- Runner::runPHPCS() and Runner::runPHPCBF() now return an exit code instead of exiting directly (request #1484) +- The Squiz standard now enforces short array syntax by default +- The autoloader is now working correctly with classes created with class_alias() +- The autoloader will now search for files inside all directories in the installed_paths config var + - This allows autoloading of files inside included custom coding standards without manually requiring them +- You can now specify a namespace for a custom coding standard, used by the autoloader to load non-sniff helper files + - Also used by the autoloader to help other standards directly include sniffs for your standard + - Set the value to the namespace prefix you are using for sniff files (everything up to \Sniffs\) + - e.g., if your namespace format is MyProject\CS\Standard\Sniffs\Category set the namespace to MyProject\CS\Standard + - If omitted, the namespace is assumed to be the same as the directory name containing the ruleset.xml file + - The namespace is set in the ruleset tag of the ruleset.xml file + - e.g., ruleset name="My Coding Standard" namespace="MyProject\CS\Standard" +- Rulesets can now specify custom autoloaders using the new autoload tag + - Autoloaders are included while the ruleset is being processed and before any custom sniffs are included + - Allows for very custom autoloading of helper classes well before the boostrap files are included +- The PEAR standard now includes Squiz.Commenting.DocCommentAlignment + - It previously broke comments onto multiple lines, but didn't align them + +### Fixed +- Fixed a problem where excluding a message from a custom standard's own sniff would exclude the whole sniff + - This caused some PSR2 errors to be under-reported +- Fixed bug #1442 : T_NULLABLE detection not working for nullable parameters and return type hints in some cases +- Fixed bug #1447 : Running the unit tests with a phpunit config file breaks the test suite + - Unknown arguments were not being handled correctly, but are now stored in $config->unknown +- Fixed bug #1449 : Generic.Classes.OpeningBraceSameLine doesn't detect comment before opening brace + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1450 : Coding standard located under an installed_path with the same directory name throws an error + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1451 : Sniff exclusions/restrictions dont work with custom sniffs unless they use the PHP_CodeSniffer NS +- Fixed bug #1454 : Squiz.WhiteSpace.OperatorSpacing is not checking spacing on either side of a short ternary operator + - Thanks to [Mponos George][@gmponos] for the patch +- Fixed bug #1495 : Setting an invalid installed path breaks all commands +- Fixed bug #1496 : Squiz.Strings.DoubleQuoteUsage not unescaping dollar sign when fixing + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #1501 : Interactive mode is broken +- Fixed bug #1504 : PSR2.Namespaces.UseDeclaration hangs fixing use statement with no trailing code + +## [2.9.1] - 2017-05-22 +### Fixed +- Fixed bug #1442 : T_NULLABLE detection not working for nullable parameters and return type hints in some cases +- Fixed bug #1448 : Generic.Classes.OpeningBraceSameLine doesn't detect comment before opening brace + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch + +## [3.0.0] - 2017-05-04 +### Changed +- Added an --ignore-annotations command line argument to ignore all @codingStandards annotations in code comments (request #811) +- This allows you to force errors to be shown that would otherwise be ignored by code comments + - Also stop files being able to change sniff properties mid way through processing +- An error is now reported if no sniffs were registered to be run (request #1129) +- The autoloader will now search for files inside the directory of any loaded coding standard + - This allows autoloading of any file inside a custom coding standard without manually requiring them + - Ensure your namespace begins with your coding standard's directory name and follows PSR-4 + - e.g., StandardName\Sniffs\CategoryName\AbstractHelper or StandardName\Helpers\StringSniffHelper +- Fixed an error where STDIN was sometimes not checked when using the --parallel CLI option +- The is_closure index has been removed from the return value of File::getMethodProperties() + - This value was always false because T_FUNCTION tokens are never closures + - Closures have a token type of T_CLOSURE +- The File::isAnonymousFunction() method has been removed + - This function always returned false because it only accepted T_FUNCTION tokens, which are never closures + - Closures have a token type of T_CLOSURE +- Includes all changes from the 2.9.0 release + +### Fixed +- Fixed bug #834 : PSR2.ControlStructures.SwitchDeclaration does not handle if branches with returns + - Thanks to [Fabian Wiget][@fabacino] for the patch + +## [3.0.0RC4] - 2017-03-02 +### Security +- This release contains a fix for a security advisory related to the improper handling of shell commands + - Uses of shell_exec() and exec() were not escaping filenames and configuration settings in most cases + - A properly crafted filename or configuration option would allow for arbitrary code execution when using some features + - All users are encouraged to upgrade to this version, especially if you are checking 3rd-party code + - e.g., you run PHPCS over libraries that you did not write + - e.g., you provide a web service that runs PHPCS over user-uploaded files or 3rd-party repositories + - e.g., you allow external tool paths to be set by user-defined values + - If you are unable to upgrade but you check 3rd-party code, ensure you are not using the following features: + - The diff report + - The notify-send report + - The Generic.PHP.Syntax sniff + - The Generic.Debug.CSSLint sniff + - The Generic.Debug.ClosureLinter sniff + - The Generic.Debug.JSHint sniff + - The Squiz.Debug.JSLint sniff + - The Squiz.Debug.JavaScriptLint sniff + - The Zend.Debug.CodeAnalyzer sniff + - Thanks to [Klaus Purer][@klausi] for the report + +### Changed +- The indent property of PEAR.Classes.ClassDeclaration has been removed + - Instead of calculating the indent of the brace, it just ensures the brace is aligned with the class keyword + - Other sniffs can be used to ensure the class itself is indented correctly +- Invalid exclude rules inside a ruleset.xml file are now ignored instead of potentially causing out of memory errors + - Using the -vv command line argument now also shows the invalid exclude rule as XML +- Includes all changes from the 2.8.1 release + +### Fixed +- Fixed bug #1333 : The new autoloader breaks some frameworks with custom autoloaders +- Fixed bug #1334 : Undefined offset when explaining standard with custom sniffs + +## [3.0.0RC3] - 2017-02-02 +### Changed +- Added support for ES6 class declarations + - Previously, these class were tokenized as JS objects but are now tokenized as normal T_CLASS structures +- Added support for ES6 method declarations, where the "function" keyword is not used + - Previously, these methods were tokenized as JS objects (fixes bug #1251) + - The name of the ES6 method is now assigned the T_FUNCTION keyword and treated like a normal function + - Custom sniffs that support JS and listen for T_FUNCTION tokens can't assume the token represents the word "function" + - Check the contents of the token first, or use $phpcsFile->getDeclarationName($stackPtr) if you just want its name + - There is no change for custom sniffs that only check PHP code +- PHPCBF exit codes have been changed so they are now more useful (request #1270) + - Exit code 0 is now used to indicate that no fixable errors were found, and so nothing was fixed + - Exit code 1 is now used to indicate that all fixable errors were fixed correctly + - Exit code 2 is now used to indicate that PHPCBF failed to fix some of the fixable errors it found + - Exit code 3 is now used for general script execution errors +- Added PEAR.Commenting.FileComment.ParamCommentAlignment to check alignment of multi-line param comments +- Includes all changes from the 2.8.0 release + +### Fixed +- Fixed an issue where excluding a file using a @codingStandardsIgnoreFile comment would produce errors + - For PHPCS, it would show empty files being processed + - For PHPCBF, it would produce a PHP error +- Fixed bug #1233 : Can't set config data inside ruleset.xml file +- Fixed bug #1241 : CodeSniffer.conf not working with 3.x PHAR file + +## [3.0.0RC2] - 2016-11-30 +### Changed +- Made the Runner class easier to use with wrapper scripts +- Full usage information is no longer printed when a usage error is encountered (request #1186) + - Makes it a lot easier to find and read the error message that was printed +- Includes all changes from the 2.7.1 release + +### Fixed +- Fixed an undefined var name error that could be produced while running PHPCBF +- Fixed bug #1167 : 3.0.0RC1 PHAR does not work with PEAR standard +- Fixed bug #1208 : Excluding files doesn't work when using STDIN with a filename specified + +## [3.0.0RC1] - 2016-09-02 +### Changed +- Progress output now shows E and W in green when a file has fixable errors or warnings + - Only supported if colors are enabled +- PHPCBF no longer produces verbose output by default (request #699) + - Use the -v command line argument to show verbose fixing output + - Use the -q command line argument to disable verbose information if enabled by default +- PHPBF now prints a summary report after fixing files + - Report shows files that were fixed, how many errors were fixed, and how many remain +- PHPCBF now supports the -p command line argument to print progress information + - Prints a green F for files where fixes occurred + - Prints a red E for files that could not be fixed due to an error + - Use the -q command line argument to disable progress information if enabled by default +- Running unit tests using --verbose no longer throws errors +- Includes all changes from the 2.7.0 release + +### Fixed +- Fixed shell error appearing on some systems when trying to find executable paths + +## [3.0.0a1] - 2016-07-20 +### Changed +- Min PHP version increased from 5.1.2 to 5.4.0 +- Added optional caching of results between runs (request #530) + - Enable the cache by using the --cache command line argument + - If you want the cache file written somewhere specific, use --cache=/path/to/cacheFile + - Use the command "phpcs --config-set cache true" to turn caching on by default + - Use the --no-cache command line argument to disable caching if it is being turned on automatically +- Add support for checking file in parallel (request #421) + - Tell PHPCS how many files to check at once using the --parallel command line argument + - To check 100 files at once, using --parallel=100 + - To disable parallel checking if it is being turned on automatically, use --parallel=1 + - Requires PHP to be compiled with the PCNTL package +- The default encoding has been changed from iso-8859-1 to utf-8 (request #760) + - The --encoding command line argument still works, but you no longer have to set it to process files as utf-8 + - If encoding is being set to utf-8 in a ruleset or on the CLI, it can be safely removed + - If the iconv PHP extension is not installed, standard non-multibyte aware functions will be used +- Added a new "code" report type to show a code snippet for each error (request #419) + - The line containing the error is printed, along with 2 lines above and below it to show context + - The location of the errors is underlined in the code snippet if you also use --colors + - Use --report=code to generate this report +- Added support for custom filtering of the file list + - Developers can write their own filter classes to perform custom filtering of the list before the run starts + - Use the command line arg --filter=/path/to/filter.php to specify a filter to use + - Extend \PHP_CodeSniffer\Filters\Filter to also support the core PHPCS extension and path filtering + - Extend \PHP_CodeSniffer\Filters\ExactMatch to get the core filtering and the ability to use blacklists and whitelists + - The included \PHP_CodeSniffer\Filters\GitModified filter is a good example of an ExactMatch filter +- Added support for only checking files that have been locally modified or added in a git repo + - Use --filter=gitmodified to check these files + - You still need to give PHPCS a list of files or directories in which to check +- Added automatic discovery of executable paths (request #571) + - Thanks to [Sergei Morozov][@morozov] for the patch +- You must now pass "-" on the command line to have PHPCS wait for STDIN + - E.g., phpcs --standard=PSR2 - + - You can still pipe content via STDIN as normal as PHPCS will see this and process it + - But without the "-", PHPCS will throw an error if no content or files are passed to it +- All PHP errors generated by sniffs are caught, re-thrown as exceptions, and reported in the standard error reports + - This should stop bugs inside sniffs causing infinite loops + - Also stops invalid reports being produced as errors don't print to the screen directly +- Sniff codes are no longer optional + - If a sniff throws and error or a warning, it must specify an internal code for that message +- The installed_paths config setting can now point directly to a standard + - Previously, it had to always point to the directory in which the standard lives +- Multiple reports can now be specified using the --report command line argument + - Report types are separated by commas + - E.g., --report=full,summary,info + - Previously, you had to use one argument for each report such as --report=full --report=summary --report=info +- You can now set the severity, message type, and exclude patterns for and entire sniff, category, or standard + - Previously, this was only available for a single message +- You can now include a single sniff code in a ruleset instead of having to include an entire sniff + - Including a sniff code will automatically exclude all other messages from that sniff + - If the sniff is already included by an imported standard, set the sniff severity to 0 and include the specific message you want +- PHPCBF no longer uses patch + - Files are now always overwritten + - The --no-patch option has been removed +- Added a --basepath option to strip a directory from the front of file paths in output (request #470) + - The basepath is absolute or relative to the current directory + - E.g., to output paths relative to current dir in reports, use --basepath=. +- Ignore rules are now checked when using STDIN (request #733) +- Added an include-pattern tag to rulesets to include a sniff for specific files and folders only (request #656) + - This is the exact opposite of the exclude-pattern tag + - This option is only usable within sniffs, not globally like exclude-patterns are +- Added a new -m option to stop error messages from being recorded, which saves a lot of memory + - PHPCBF always uses this setting to reduce memory as it never outputs error messages + - Setting the $recordErrors member var inside custom report classes is no longer supported (use -m instead) +- Exit code 2 is now used to indicate fixable errors were found (request #930) + - Exit code 3 is now used for general script execution errors + - Exit code 1 is used to indicate that coding standard errors were found, but none are fixable + - Exit code 0 is unchanged and continues to mean no coding standard errors found + +### Removed +- The included PHPCS standard has been removed + - All rules are now found inside the phpcs.xml.dist file + - Running "phpcs" without any arguments from a git clone will use this ruleset +- The included SVN pre-commit hook has been removed + - Hooks for version control systems will no longer be maintained within the PHPCS project + +## [2.9.0] - 2017-05-04 +### Changed +- Added Generic.Debug.ESLint sniff to run ESLint over JS files and report errors + - Set eslint path using: phpcs --config-set eslint_path /path/to/eslint + - Thanks to [Ryan McCue][@rmccue] for the contribution +- T_POW is now properly considered an arithmetic operator, and will be checked as such + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- T_SPACESHIP and T_COALESCE are now properly considered comparison operators, and will be checked as such + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHP.DisallowShortOpenTag now warns about possible short open tags even when short_open_tag is set to OFF + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.WhiteSpace.DisallowTabIndent now finds and fixes improper use of spaces anywhere inside the line indent + - Previously, only the first part of the indent was used to determine the indent type + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.Commenting.ClassComment now supports checking of traits as well as classes and interfaces + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.FunctionCommentThrowTag now supports re-throwing exceptions (request #946) + - Thanks to [Samuel Levy][@samlev] for the patch +- Squiz.PHP.DisallowMultipleAssignments now ignores PHP4-style member var assignments + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.FunctionSpacing now ignores spacing above functions when they are preceded by inline comments + - Stops conflicts between this sniff and comment spacing sniffs +- Squiz.WhiteSpace.OperatorSpacing no longer checks the equal sign in declare statements + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added missing error codes for a couple of sniffs so they can now be customised as normal + +### Fixed +- Fixed bug #1266 : PEAR.WhiteSpace.ScopeClosingBrace can throw an error while fixing mixed PHP/HTML +- Fixed bug #1364 : Yield From values are not recognised as returned values in Squiz FunctionComment sniff +- Fixed bug #1373 : Error in tab expansion results in white-space of incorrect size + - Thanks to [Mark Clements][@MarkMaldaba] for the patch +- Fixed bug #1381 : Tokenizer: dereferencing incorrectly identified as short array +- Fixed bug #1387 : Squiz.ControlStructures.ControlSignature does not handle alt syntax when checking space after closing brace +- Fixed bug #1392 : Scope indent calculated incorrectly when using array destructuring +- Fixed bug #1394 : integer type hints appearing as TypeHintMissing instead of ScalarTypeHintMissing + - PHP 7 type hints were also being shown when run under PHP 5 in some cases +- Fixed bug #1405 : Squiz.WhiteSpace.ScopeClosingBrace fails to fix closing brace within indented PHP tags +- Fixed bug #1421 : Ternaries used in constant scalar expression for param default misidentified by tokenizer +- Fixed bug #1431 : PHPCBF can't fix short open tags when they are not followed by a space + - Thanks to [Gonçalo Queirós][@ghunti] for the patch +- Fixed bug #1432 : PHPCBF can make invalid fixes to inline JS control structures that make use of JS objects + +## [2.8.1] - 2017-03-02 +### Security +- This release contains a fix for a security advisory related to the improper handling of shell commands + - Uses of shell_exec() and exec() were not escaping filenames and configuration settings in most cases + - A properly crafted filename or configuration option would allow for arbitrary code execution when using some features + - All users are encouraged to upgrade to this version, especially if you are checking 3rd-party code + - e.g., you run PHPCS over libraries that you did not write + - e.g., you provide a web service that runs PHPCS over user-uploaded files or 3rd-party repositories + - e.g., you allow external tool paths to be set by user-defined values + - If you are unable to upgrade but you check 3rd-party code, ensure you are not using the following features: + - The diff report + - The notify-send report + - The Generic.PHP.Syntax sniff + - The Generic.Debug.CSSLint sniff + - The Generic.Debug.ClosureLinter sniff + - The Generic.Debug.JSHint sniff + - The Squiz.Debug.JSLint sniff + - The Squiz.Debug.JavaScriptLint sniff + - The Zend.Debug.CodeAnalyzer sniff + - Thanks to [Klaus Purer][@klausi] for the report + +### Changed +- The PHP-supplied T_COALESCE_EQUAL token has been replicated for PHP versions before 7.2 +- PEAR.Functions.FunctionDeclaration now reports an error for blank lines found inside a function declaration +- PEAR.Functions.FunctionDeclaration no longer reports indent errors for blank lines in a function declaration +- Squiz.Functions.MultiLineFunctionDeclaration no longer reports errors for blank lines in a function declaration + - It would previously report that only one argument is allowed per line +- Squiz.Commenting.FunctionComment now corrects multi-line param comment padding more accurately +- Squiz.Commenting.FunctionComment now properly fixes pipe-separated param types +- Squiz.Commenting.FunctionComment now works correctly when function return types also contain a comment + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.ControlStructures.InlineIfDeclaration now supports the elvis operator + - As this is not a real PHP operator, it enforces no spaces between ? and : when the THEN statement is empty +- Squiz.ControlStructures.InlineIfDeclaration is now able to fix the spacing errors it reports + +### Fixed +- Fixed bug #1340 : STDIN file contents not being populated in some cases + - Thanks to [David Biňovec][@david-binda] for the patch +- Fixed bug #1344 : PEAR.Functions.FunctionCallSignatureSniff throws error for blank comment lines +- Fixed bug #1347 : PSR2.Methods.FunctionCallSignature strips some comments during fixing + - Thanks to [Algirdas Gurevicius][@uniquexor] for the patch +- Fixed bug #1349 : Squiz.Strings.DoubleQuoteUsage.NotRequired message is badly formatted when string contains a CR newline char + - Thanks to [Algirdas Gurevicius][@uniquexor] for the patch +- Fixed bug #1350 : Invalid Squiz.Formatting.OperatorBracket error when using namespaces +- Fixed bug #1369 : Empty line in multi-line function declaration cause infinite loop + +## [2.8.0] - 2017-02-02 +### Changed +- The Internal.NoCodeFound error is no longer generated for content sourced from STDIN + - This should stop some Git hooks generating errors because PHPCS is trying to process the refs passed on STDIN +- Squiz.Commenting.DocCommentAlignment now checks comments on class properties defined using the VAR keyword + - Thanks to [Klaus Purer][@klausi] for the patch +- The getMethodParameters() method now recognises "self" as a valid type hint + - The return array now contains a new "content" index containing the raw content of the param definition + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The getMethodParameters() method now supports nullable types + - The return array now contains a new "nullable_type" index set to true or false for each method param + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The getMethodParameters() method now supports closures + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added more guard code for JS files with syntax errors (request #1271 and request #1272) +- Added more guard code for CSS files with syntax errors (request #1304) +- PEAR.Commenting.FunctionComment fixers now correctly handle multi-line param comments +- AbstractVariableSniff now supports anonymous classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.NamingConventions.ConstructorName and PEAR.NamingConventions.ValidVariable now support anonymous classes +- Generic.NamingConventions.CamelCapsFunctionName and PEAR.NamingConventions.ValidFunctionName now support anonymous classes + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.CodeAnalysis.UnusedFunctionParameter and PEAR.Functions.ValidDefaultValue now support closures + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- PEAR.NamingConventions.ValidClassName and Squiz.Classes.ValidClassName now support traits + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.Functions.FunctionCallArgumentSpacing now supports closures other PHP-provided functions + - Thanks to [Algirdas Gurevicius][@uniquexor] for the patch +- Fixed an error where a nullable type character was detected as an inline then token + - A new T_NULLABLE token has been added to represent the ? nullable type character + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Squiz.WhiteSpace.SemicolonSpacing no longer removes comments while fixing the placement of semicolons + - Thanks to [Algirdas Gurevicius][@uniquexor] for the patch + +### Fixed +- Fixed bug #1230 : JS tokeniser incorrectly tokenises bitwise shifts as comparison + - Thanks to [Ryan McCue][@rmccue] for the patch +- Fixed bug #1237 : Uninitialized string offset in PHP Tokenizer on PHP 5.2 +- Fixed bug #1239 : Warning when static method name is 'default' +- Fixed bug #1240 : False positive for function names starting with triple underscore + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1245 : SELF is not recognised as T_SELF token in: return new self +- Fixed bug #1246 : A mix of USE statements with and without braces can cause the tokenizer to mismatch brace tokens + - Thanks to [Michał Bundyra][@michalbundyra] for the patch +- Fixed bug #1249 : GitBlame report requires a .git directory +- Fixed bug #1252 : Squiz.Strings.ConcatenationSpacing fix creates syntax error when joining a number to a string +- Fixed bug #1253 : Generic.ControlStructures.InlineControlStructure fix creates syntax error fixing if-try/catch +- Fixed bug #1255 : Inconsistent indentation check results when ELSE on new line +- Fixed bug #1257 : Double dash in CSS class name can lead to "Named colours are forbidden" false positives +- Fixed bug #1260 : Syntax errors not being shown when error_prepend_string is set + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Fixed bug #1264 : Array return type hint is sometimes detected as T_ARRAY_HINT instead of T_RETURN_TYPE + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #1265 : ES6 arrow function raises unexpected operator spacing errors +- Fixed bug #1267 : Fixer incorrectly handles filepaths with repeated dir names + - Thanks to [Sergey Ovchinnikov][@orx0r] for the patch +- Fixed bug #1276 : Commenting.FunctionComment.InvalidReturnVoid conditional issue with anonymous classes +- Fixed bug #1277 : Squiz.PHP.DisallowMultipleAssignments.Found error when var assignment is on the same line as an open tag +- Fixed bug #1284 : Squiz.Arrays.ArrayBracketSpacing.SpaceBeforeBracket false positive match for short list syntax + +## [2.7.1] - 2016-11-30 +### Changed +- Squiz.ControlStructures.ControlSignature.SpaceAfterCloseParenthesis fix now removes unnecessary whitespace +- Squiz.Formatting.OperatorBracket no longer errors for negative array indexes used within a function call +- Squiz.PHP.EmbeddedPhp no longer expects a semicolon after statements that are only opening a scope +- Fixed a problem where the content of T_DOC_COMMENT_CLOSE_TAG tokens could sometimes be (boolean) false +- Developers of custom standards with custom test runners can now have their standards ignored by the built-in test runner + - Set the value of an environment variable called PHPCS_IGNORE_TESTS with a comma separated list of your standard names + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- The unit test runner now loads the test sniff outside of the standard's ruleset so that exclude rules do not get applied + - This may have caused problems when testing custom sniffs inside custom standards + - Also makes the unit tests runs a little faster +- The SVN pre-commit hook now works correctly when installed via composer + - Thanks to [Sergey][@sserbin] for the patch + +### Fixed +- Fixed bug #1135 : PEAR.ControlStructures.MultiLineCondition.CloseBracketNewLine not detected if preceded by multiline function call +- Fixed bug #1138 : PEAR.ControlStructures.MultiLineCondition.Alignment not detected if closing brace is first token on line +- Fixed bug #1141 : Sniffs that check EOF newlines don't detect newlines properly when the last token is a doc block +- Fixed bug #1150 : Squiz.Strings.EchoedStrings does not properly fix bracketed statements +- Fixed bug #1156 : Generic.Formatting.DisallowMultipleStatements errors when multiple short echo tags are used on the same line + - Thanks to [Nikola Kovacs][@nkovacs] for the patch +- Fixed bug #1161 : Absolute report path is treated like a relative path if it also exists within the current directory +- Fixed bug #1170 : Javascript regular expression literal not recognized after comparison operator +- Fixed bug #1180 : Class constant named FUNCTION is incorrectly tokenized +- Fixed bug #1181 : Squiz.Operators.IncrementDecrementUsage.NoBrackets false positive when incrementing properties + - Thanks to [Jürgen Henge-Ernst][@hernst42] for the patch +- Fixed bug #1188 : Generic.WhiteSpace.ScopeIndent issues with inline HTML and multi-line function signatures +- Fixed bug #1190 : phpcbf on if/else with trailing comment generates erroneous code +- Fixed bug #1191 : Javascript sniffer fails with function called "Function" +- Fixed bug #1203 : Inconsistent behavior of PHP_CodeSniffer_File::findEndOfStatement +- Fixed bug #1218 : CASE conditions using class constants named NAMESPACE/INTERFACE/TRAIT etc are incorrectly tokenized +- Fixed bug #1221 : Indented function call with multiple closure arguments can cause scope indent error +- Fixed bug #1224 : PHPCBF fails to fix code with heredoc/nowdoc as first argument to a function + +## [2.7.0] - 2016-09-02 +### Changed +- Added --file-list command line argument to allow a list of files and directories to be specified in an external file + - Useful is you have a generated list of files to check that would be too long for the command line + - File and directory paths are listed one per line + - Usage is: phpcs --file-list=/path/to/file-list ... + - Thanks to [Blotzu][@andrei-propertyguru] for the patch +- Values set using @codingStandardsChangeSetting comments can now contain spaces +- Sniff unit tests can now specify a list of test files instead of letting the runner pick them (request #1078) + - Useful if a sniff needs to exclude files based on the environment, or is checking filenames + - Override the new getTestFiles() method to specify your own list of test files +- Generic.Functions.OpeningFunctionBraceKernighanRitchie now ignores spacing for function return types + - The sniff code Generic.Functions.OpeningFunctionBraceKernighanRitchie.SpaceAfterBracket has been removed + - Replaced by Generic.Functions.OpeningFunctionBraceKernighanRitchie.SpaceBeforeBrace + - The new error message is slightly clearer as it indicates that a single space is needed before the brace +- Squiz.Commenting.LongConditionClosingComment now allows for the length of a code block to be configured + - Set the lineLimit property (default is 20) in your ruleset.xml file to set the code block length + - When the code block length is reached, the sniff will enforce a closing comment after the closing brace + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.Commenting.LongConditionClosingComment now allows for the end comment format to be configured + - Set the commentFormat property (default is "//end %s") in your ruleset.xml file to set the format + - The placeholder %s will be replaced with the type of condition opener, e.g., "//end foreach" + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Generic.PHPForbiddenFunctions now allows forbidden functions to have mixed case + - Previously, it would only do a strtolower comparison + - Error message now shows what case was found in the code and what the correct case should be + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added Generic.Classes.OpeningBraceSameLine to ensure opening brace of class/interface/trait is on the same line as the declaration + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added Generic.PHP.BacktickOperator to ban the use of the backtick operator for running shell commands + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Added Generic.PHP.DisallowAlternativePHPTags to ban the use of alternate PHP tags + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Squiz.WhiteSpace.LanguageConstructSpacing no longer checks for spaces if parenthesis are being used (request #1062) + - Makes this sniff more compatible with those that check parenthesis spacing of function calls +- Squiz.WhiteSpace.ObjectOperatorSpacing now has a setting to ignore newline characters around object operators + - Default remains FALSE, so newlines are not allowed + - Override the "ignoreNewlines" setting in a ruleset.xml file to change + - Thanks to [Alex Howansky][@AlexHowansky] for the patch +- Squiz.Scope.MethodScope now sniffs traits as well as classes and interfaces + - Thanks to [Jesse Donat][@donatj] for the patch +- PHPCBF is now able to fix Squiz.SelfMemberReference.IncorrectCase errors + - Thanks to [Nikola Kovacs][@nkovacs] for the patch +- PHPCBF is now able to fix Squiz.Commenting.VariableComment.IncorrectVarType + - Thanks to [Walt Sorensen][@photodude] for the patch +- PHPCBF is now able to fix Generic.PHP.DisallowShortOpenTag + - Thanks to [Juliette Reinders Folmer][@jrfnl] for the patch +- Improved the formatting of the end brace when auto fixing InlineControlStructure errors (request #1121) +- Generic.Functions.OpeningFunctionBraceKernighanRitchie.BraceOnNewLine fix no longer leaves blank line after brace (request #1085) +- Generic UpperCaseConstantNameSniff now allows lowercase namespaces in constant definitions + - Thanks to [Daniel Schniepp][@dschniepp] for the patch +- Squiz DoubleQuoteUsageSniff is now more tolerant of syntax errors caused by mismatched string tokens +- A few sniffs that produce errors based on the current PHP version can now be told to run using a specific PHP version + - Set the php_version config var using --config-set, --runtime-set, or in a ruleset to specify a specific PHP version + - The format of the PHP version is the same as the PHP_VERSION_ID constant (e.g., 50403 for version 5.4.3) + - Supported sniffs are Generic.PHP.DisallowAlternativePHPTags, PSR1.Classes.ClassDeclaration, Squiz.Commenting.FunctionComment + - Thanks to [Finlay Beaton][@ofbeaton] for the patch + +### Fixed +- Fixed bug #985 : Duplicate class definition detection generates false-positives in media queries + - Thanks to [Raphael Horber][@rhorber] for the patch +- Fixed bug #1014 : Squiz VariableCommentSniff doesn't always detect a missing comment +- Fixed bug #1066 : Undefined index: quiet in CLI.php during unit test run with -v command line arg +- Fixed bug #1072 : Squiz.SelfMemberReference.NotUsed not detected if leading namespace separator is used +- Fixed bug #1089 : Rulesets cannot be loaded if the path contains urlencoded characters +- Fixed bug #1091 : PEAR and Squiz FunctionComment sniffs throw errors for some invalid @param line formats +- Fixed bug #1092 : PEAR.Functions.ValidDefaultValue should not flag type hinted methods with a NULL default argument +- Fixed bug #1095 : Generic LineEndings sniff replaces tabs with spaces with --tab-width is set +- Fixed bug #1096 : Squiz FunctionDeclarationArgumentSpacing gives incorrect error/fix when variadic operator is followed by a space +- Fixed bug #1099 : Group use declarations are incorrectly fixed by the PSR2 standard + - Thanks to [Jason McCreary][@jasonmccreary] for the patch +- Fixed bug #1101 : Incorrect indent errors when breaking out of PHP inside an IF statement +- Fixed bug #1102 : Squiz.Formatting.OperatorBracket.MissingBrackets faulty bracketing fix +- Fixed bug #1109 : Wrong scope indent reported in anonymous class +- Fixed bug #1112 : File docblock not recognized when require_once follows it +- Fixed bug #1120 : InlineControlStructureSniff does not handle auto-fixing for control structures that make function calls +- Fixed bug #1124 : Squiz.Operators.ComparisonOperatorUsage does not detect bracketed conditions for inline IF statements + - Thanks to [Raphael Horber][@rhorber] for the patch + +## [2.6.2] - 2016-07-14 +### Changed +- Added a new --exclude CLI argument to exclude a list of sniffs from checking and fixing (request #904) + - Accepts the same sniff codes as the --sniffs command line argument, but provides the opposite functionality +- Added a new -q command line argument to disable progress and verbose information from being printed (request #969) + - Useful if a coding standard hard-codes progress or verbose output but you want PHPCS to be quiet + - Use the command "phpcs --config-set quiet true" to turn quiet mode on by default +- Generic LineLength sniff no longer errors for comments that cannot be broken out onto a new line (request #766) + - A typical case is a comment that contains a very long URL + - The comment is ignored if putting the URL on a indented new comment line would be longer than the allowed length +- Settings extensions in a ruleset no longer causes PHP notices during unit testing + - Thanks to [Klaus Purer][@klausi] for the patch +- Version control reports now show which errors are fixable if you are showing sources +- Added a new sniff to enforce a single space after a NOT operator (request #1051) + - Include in a ruleset using the code Generic.Formatting.SpaceAfterNot +- The Squiz.Commenting.BlockComment sniff now supports tabs for indenting comment lines (request #1056) + +### Fixed +- Fixed bug #790 : Incorrect missing @throws error in methods that use closures +- Fixed bug #908 : PSR2 standard is not checking that closing brace is on line following the body +- Fixed bug #945 : Incorrect indent behavior using deep-nested function and arrays +- Fixed bug #961 : Two anonymous functions passed as function/method arguments cause indentation false positive +- Fixed bug #1005 : Using global composer vendor autoload breaks PHP lowercase built-in function sniff + - Thanks to [Michael Butler][@michaelbutler] for the patch +- Fixed bug #1007 : Squiz Unreachable code detection is not working properly with a closure inside a case +- Fixed bug #1023 : PSR2.Classes.ClassDeclaration fails if class extends base class and "implements" is on trailing line +- Fixed bug #1026 : Arrays in comma delimited class properties cause ScopeIndent to increase indent +- Fixed bug #1028 : Squiz ArrayDeclaration incorrectly fixes multi-line array where end bracket is not on a new line +- Fixed bug #1034 : Squiz FunctionDeclarationArgumentSpacing gives incorrect error when first arg is a variadic +- Fixed bug #1036 : Adjacent assignments aligned analysis statement wrong +- Fixed bug #1049 : Version control reports can show notices when the report width is very small +- Fixed bug #21050 : PEAR MultiLineCondition sniff suppresses errors on last condition line + +## [2.6.1] - 2016-05-31 +### Changed +- The PHP-supplied T_COALESCE token has been replicated for PHP versions before 7.0 +- Function return types of self, parent and callable are now tokenized as T_RETURN_TYPE + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- The default_standard config setting now allows multiple standards to be listed, like on the command line + - Thanks to [Michael Mayer][@schnittstabil] for the patch +- Installations done via composer now only include the composer autoloader for PHP 5.3.2+ (request #942) +- Added a rollbackChangeset() method to the Fixer class to purposely rollback the active changeset + +### Fixed +- Fixed bug #940 : Auto-fixing issue encountered with inconsistent use of braces +- Fixed bug #943 : Squiz.PHP.InnerFunctions.NotAllowed reported in anonymous classes +- Fixed bug #944 : PHP warning when running the latest phar +- Fixed bug #951 : InlineIfDeclaration: invalid error produced with UTF-8 string +- Fixed bug #957 : Operator spacing sniff errors when plus is used as part of a number + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #959 : Call-time pass-by-reference false positive if there is a square bracket before the ampersand + - Thanks to [Konstantin Leboev][@realmfoo] for the patch +- Fixed bug #962 : Null coalescing operator (??) not detected as a token + - Thanks to [Joel Posti][@joelposti] for the patch +- Fixed bug #973 : Anonymous class declaration and PSR1.Files.SideEffects.FoundWithSymbols +- Fixed bug #974 : Error when file ends with "function" +- Fixed bug #979 : Anonymous function with return type hint is not refactored as expected +- Fixed bug #983 : Squiz.WhiteSpace.MemberVarSpacing.AfterComment fails to fix error when comment is not a docblock +- Fixed bug #1010 : Squiz NonExecutableCode sniff does not detect boolean OR + - Thanks to [Derek Henderson][@2shediac] for the patch +- Fixed bug #1015 : The Squiz.Commenting.FunctionComment sniff doesn't allow description in @return tag + - Thanks to [Alexander Obuhovich][@aik099] for the patch +- Fixed bug #1022 : Duplicate spaces after opening bracket error with PSR2 standard +- Fixed bug #1025 : Syntax error in JS file can cause undefined index for parenthesis_closer + +## [2.6.0] - 2016-04-04 +### Changed +- Paths used when setting CLI arguments inside ruleset.xml files are now relative to the ruleset location (request #847) + - This change only applies to paths within ARG tags, used to set CLI arguments + - Previously, the paths were relative to the directory PHPCS was being run from + - Absolute paths are still allowed and work the same way they always have + - This change allows ruleset.xml files to be more portable +- Content passed via STDIN will now be processed even if files are specified on the command line or in a ruleset +- When passing content via STDIN, you can now specify the file path to use on the command line (request #934) + - This allows sniffs that check file paths to work correctly + - This is the same functionality provided by the phpcs_input_file line, except it is available on the command line +- Files processed with custom tokenizers will no longer be skipped if they appear minified (request #877) + - If the custom tokenizer wants minified files skipped, it can set a $skipMinified member var to TRUE + - See the included JS and CSS tokenizers for an example +- Config vars set in ruleset.xml files are now processed earlier, allowing them to be used during sniff registration + - Among other things, this allows the installed_paths config var to be set in ruleset.xml files + - Thanks to [Pieter Frenssen][@pfrenssen] for the patch +- Improved detection of regular expressions in the JS tokenizer +- Generic PHP Syntax sniff now uses PHP_BINARY (if available) to determine the path to PHP if no other path is available + - You can still manually set php_path to use a specific binary for testing + - Thanks to [Andrew Berry][@deviantintegral] for the patch +- The PHP-supplied T_POW_EQUAL token has been replicated for PHP versions before 5.6 +- Added support for PHP7 use group declarations (request #878) + - New tokens T_OPEN_USE_GROUP and T_CLOSE_USE_GROUP are assigned to the open and close curly braces +- Generic ScopeIndent sniff now reports errors for every line that needs the indent changed (request #903) + - Previously, it ignored lines that were indented correctly in the context of their block + - This change produces more technically accurate error messages, but is much more verbose +- The PSR2 and Squiz standards now allow multi-line default values in function declarations (request #542) + - Previously, these would automatically make the function a multi-line declaration +- Squiz InlineCommentSniff now allows docblocks on require(_once) and include(_once) statements + - Thanks to [Gary Jones][@GaryJones] for the patch +- Squiz and PEAR Class and File sniffs no longer assume the first comment in a file is always a file comment + - phpDocumentor assigns the comment to the file only if it is not followed by a structural element + - These sniffs now follow this same rule +- Squiz ClassCommentSniff no longer checks for blank lines before class comments + - Removes the error Squiz.Commenting.ClassComment.SpaceBefore +- Renamed Squiz.CSS.Opacity.SpacingAfterPoint to Squiz.CSS.Opacity.DecimalPrecision + - Please update your ruleset if you are referencing this error code directly +- Fixed PHP tokenizer problem that caused an infinite loop when checking a comment with specific content +- Generic Disallow Space and Tab indent sniffs now detect and fix indents inside embedded HTML chunks (request #882) +- Squiz CSS IndentationSniff no longer assumes the class opening brace is at the end of a line +- Squiz FunctionCommentThrowTagSniff now ignores non-docblock comments +- Squiz ComparisonOperatorUsageSniff now allows conditions like while(true) +- PEAR FunctionCallSignatureSniff (and the Squiz and PSR2 sniffs that use it) now correctly check the first argument + - Further fix for bug #698 + +### Fixed +- Fixed bug #791 : codingStandardsChangeSetting settings not working with namespaces +- Fixed bug #872 : Incorrect detection of blank lines between CSS class names +- Fixed bug #879 : Generic InlineControlStructureSniff can create parse error when case/if/elseif/else have mixed brace and braceless definitions +- Fixed bug #883 : PSR2 is not checking for blank lines at the start and end of control structures +- Fixed bug #884 : Incorrect indentation notice for anonymous classes +- Fixed bug #887 : Using curly braces for a shared CASE/DEFAULT statement can generate an error in PSR2 SwitchDeclaration +- Fixed bug #889 : Closure inside catch/else/elseif causes indentation error +- Fixed bug #890 : Function call inside returned short array value can cause indentation error inside CASE statements +- Fixed bug #897 : Generic.Functions.CallTimePassByReference.NotAllowed false positive when short array syntax +- Fixed bug #900 : Squiz.Functions.FunctionDeclarationArgumentSpacing bug when no space between type hint and argument +- Fixed bug #902 : T_OR_EQUAL and T_POW_EQUAL are not seen as assignment tokens +- Fixed bug #910 : Unrecognized "extends" and indentation on anonymous classes +- Fixed bug #915 : JS Tokenizer generates errors when processing some decimals +- Fixed bug #928 : Endless loop when sniffing a PHP file with a git merge conflict inside a function +- Fixed bug #937 : Shebang can cause PSR1 SideEffects warning + - Thanks to [Clay Loveless][@claylo] for the patch +- Fixed bug #938 : CallTimePassByReferenceSniff ignores functions with return value + +## [2.5.1] - 2016-01-20 +### Changed +- The PHP-supplied T_SPACESHIP token has been replicated for PHP versions before 7.0 +- T_SPACESHIP is now correctly identified as an operator + - Thanks to [Alexander Obuhovich][@aik099] for the patch +- Generic LowerCaseKeyword now ensures array type hints are lowercase as well + - Thanks to [Mathieu Rochette][@mathroc] for the patch +- Squiz ComparisonOperatorUsageSniff no longer hangs on JS FOR loops that don't use semicolons +- PHP_CodesSniffer now includes the composer autoload.php file, if there is one + - Thanks to [Klaus Purer][@klausi] for the patch +- Added error Squiz.Commenting.FunctionComment.ScalarTypeHintMissing for PHP7 only (request #858) + - These errors were previously reported as Squiz.Commenting.FunctionComment.TypeHintMissing on PHP7 + - Disable this error message in a ruleset.xml file if your code needs to run on both PHP5 and PHP7 +- The PHP 5.6 __debugInfo magic method no longer produces naming convention errors + - Thanks to [Michael Nowack][@syranez] for the patch +- PEAR and Squiz FunctionComment sniffs now support variadic functions (request #841) + +### Fixed +- Fixed bug #622 : Wrong detection of Squiz.CSS.DuplicateStyleDefinition with media queries +- Fixed bug #752 : The missing exception error is reported in first found DocBlock +- Fixed bug #794 : PSR2 MultiLineFunctionDeclaration forbids comments after opening parenthesis of a multiline call +- Fixed bug #820 : PEAR/PSR2 FunctionCallSignature sniffs suggest wrong indent when there are multiple arguments on a line +- Fixed bug #822 : Ruleset hard-coded file paths are not used if not running from the same directory as the ruleset +- Fixed bug #825 : FunctionCallArgumentSpacing sniff complains about more than one space before comment in multi-line function call +- Fixed bug #828 : Null classname is tokenized as T_NULL instead of T_STRING +- Fixed bug #829 : Short array argument not fixed correctly when multiple function arguments are on the same line +- Fixed bug #831 : PHPCS freezes in an infinite loop under Windows if no standard is passed +- Fixed bug #832 : Tokenizer does not support context sensitive parsing + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #835 : PEAR.Functions.FunctionCallSignature broken when closure uses return types +- Fixed bug #838 : CSS indentation fixer changes color codes + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #839 : "__()" method is marked as not camel caps + - Thanks to [Tim Bezhashvyly][@tim-bezhashvyly] for the patch +- Fixed bug #852 : Generic.Commenting.DocComment not finding errors when long description is omitted +- Fixed bug #854 : Return typehints in interfaces are not reported as T_RETURN_TYPE + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #855 : Capital letter detection for multibyte strings doesn't work correctly +- Fixed bug #857 : PSR2.ControlStructure.SwitchDeclaration shouldn't check indent of curly brace closers +- Fixed bug #859 : Switch statement indention issue when returning function call with closure +- Fixed bug #861 : Single-line arrays and function calls can generate incorrect indentation errors +- Fixed bug #867 : Squiz.Strings.DoubleQuoteUsage broken for some escape codes + - Thanks to [Jack Blower][@ElvenSpellmaker] for the help with the fix +- Fixed bug #21005 : Incorrect indent detection when multiple properties are initialized to arrays +- Fixed bug #21010 : Incorrect missing colon detection in CSS when first style is not on new line +- Fixed bug #21011 : Incorrect error message text when newline found after opening brace + +## [2.5.0] - 2015-12-11 +### Changed +- PHPCS will now look for a phpcs.xml file in parent directories as well as the current directory (request #626) +- PHPCS will now use a phpcs.xml file even if files are specified on the command line + - This file is still only used if no standard is specified on the command line +- Added support for a phpcs.xml.dist file (request #583) + - If both a phpcs.xml and phpcs.xml.dist file are present, the phpcs.xml file will be used +- Added support for setting PHP ini values in ruleset.xml files (request #560) + - Setting the value of the new ini tags to name="memory_limit" value="32M" is the same as -d memory_limit=32M +- Added support for one or more bootstrap files to be run before processing begins + - Use the --bootstrap=file,file,file command line argument to include bootstrap files + - Useful if you want to override some of the high-level settings of PHPCS or PHPCBF + - Thanks to [John Maguire][@johnmaguire] for the patch +- Added additional verbose output for CSS tokenizing +- Squiz ComparisonOperatorUsageSniff now checks FOR, WHILE and DO-WHILE statements + - Thanks to [Arnout Boks][@aboks] for the patch + +### Fixed +- Fixed bug #660 : Syntax checks can fail on Windows with PHP5.6 +- Fixed bug #784 : $this->trait is seen as a T_TRAIT token +- Fixed bug #786 : Switch indent issue with short array notation +- Fixed bug #787 : SpacingAfterDefaultBreak confused by multi-line statements +- Fixed bug #797 : Parsing CSS url() value breaks further parsing +- Fixed bug #805 : Squiz.Commenting.FunctionComment.InvalidTypeHint on Scalar types on PHP7 +- Fixed bug #807 : Cannot fix line endings when open PHP tag is not on the first line +- Fixed bug #808 : JS tokeniser incorrectly setting some function and class names to control structure tokens +- Fixed bug #809 : PHPCBF can break a require_once statement with a space before the open parenthesis +- Fixed bug #813 : PEAR FunctionCallSignature checks wrong indent when first token on line is part of a multi-line string + +## [2.4.0] - 2015-11-24 +### Changed +- Added support for PHP 7 anonymous classes + - Anonymous classes are now tokenized as T_ANON_CLASS and ignored by normal class sniffs +- Added support for PHP 7 function return type declarations + - Return types are now tokenized as T_RETURN_TYPE +- Fixed tokenizing of the XOR operator, which was incorrectly identified as a power operator (bug #765) + - The T_POWER token has been removed and replaced by the T_BITWISE_XOR token + - The PHP-supplied T_POW token has been replicated for PHP versions before 5.6 +- Traits are now tokenized in PHP versions before 5.4 to make testing easier +- Improved regular expression detection in JS files +- PEAR FunctionCallSignatureSniff now properly detects indents in more mixed HTML/PHP code blocks +- Full report now properly indents lines when newlines are found inside error messages +- Generating documentation without specifying a standard now uses the default standard instead + - Thanks to [Ken Guest][@kenguest] for the patch +- Generic InlineControlStructureSniff now supports braceless do/while loops in JS + - Thanks to [Pieter Frenssen][@pfrenssen] for the patch +- Added more guard code for function declarations with syntax errors + - Thanks to Yun Young-jin for the patch +- Added more guard code for foreach declarations with syntax errors + - Thanks to [Johan de Ruijter][@johanderuijter] for the patch +- Added more guard code for class declarations with syntax errors +- Squiz ArrayDeclarationSniff now has guard code for arrays with syntax errors +- Generic InlineControlStructureSniff now correctly fixes ELSEIF statements + +### Fixed +- Fixed bug #601 : Expected type hint int[]; found array in Squiz FunctionCommentSniff + - Thanks to [Scato Eggen][@scato] for the patch +- Fixed bug #625 : Consider working around T_HASHBANG in HHVM 3.5.x and 3.6.x + - Thanks to [Kunal Mehta][@legoktm] for the patch +- Fixed bug #692 : Comment tokenizer can break when using mbstring function overloading +- Fixed bug #694 : Long sniff codes can cause PHP warnings in source report when showing error codes +- Fixed bug #698 : PSR2.Methods.FunctionCallSignature.Indent forces exact indent of ternary operator parameters +- Fixed bug #704 : ScopeIndent can fail when an opening parenthesis is on a line by itself +- Fixed bug #707 : Squiz MethodScopeSniff doesn't handle nested functions +- Fixed bug #709 : Squiz.Sniffs.Whitespace.ScopeClosingBraceSniff marking indented endif in mixed inline HTML blocks +- Fixed bug #711 : Sniffing from STDIN shows Generic.Files.LowercasedFilename.NotFound error +- Fixed bug #714 : Fixes suppression of errors using docblocks + - Thanks to [Andrzej Karmazyn][@akarmazyn] for the patch +- Fixed bug #716 : JSON report is invalid when messages contain newlines or tabs + - Thanks to [Pieter Frenssen][@pfrenssen] for the patch +- Fixed bug #723 : ScopeIndent can fail when multiple array closers are on the same line +- Fixed bug #730 : ScopeIndent can fail when a short array opening square bracket is on a line by itself +- Fixed bug #732 : PHP Notice if @package name is made up of all invalid characters + - Adds new error code PEAR.Commenting.FileComment.InvalidPackageValue +- Fixed bug #748 : Auto fix for Squiz.Commenting.BlockComment.WrongEnd is incorrect + - Thanks to [J.D. Grimes][@JDGrimes] for the patch +- Fixed bug #753 : PSR2 standard shouldn't require space after USE block when next code is a closing tag +- Fixed bug #768 : PEAR FunctionCallSignature sniff forbids comments after opening parenthesis of a multiline call +- Fixed bug #769 : Incorrect detection of variable reference operator when used with short array syntax + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #772 : Syntax error when using PHPCBF on alternative style foreach loops +- Fixed bug #773 : Syntax error when stripping trailing PHP close tag and previous statement has no semicolon +- Fixed bug #778 : PHPCBF creates invalid PHP for inline FOREACH containing multiple control structures +- Fixed bug #781 : Incorrect checking for PHP7 return types on multi-line function declarations +- Fixed bug #782 : Conditional function declarations cause fixing conflicts in Squiz standard + - Squiz.ControlStructures.ControlSignature no longer enforces a single newline after open brace + - Squiz.WhiteSpace.ControlStructureSpacing can be used to check spacing at the start/end of control structures + +## [2.3.4] - 2015-09-09 +### Changed +- JSON report format now includes the fixable status for each error message and the total number of fixable errors +- Added more guard code for function declarations with syntax errors +- Added tokenizer support for the PHP declare construct + - Thanks to [Andy Blyler][@ablyler] for the patch +- Generic UnnecessaryStringConcatSniff can now allow strings concatenated over multiple lines + - Set the allowMultiline property to TRUE (default is FALSE) in your ruleset.xml file to enable this + - By default, concat used only for getting around line length limits still generates an error + - Thanks to [Stefan Lenselink][@stefanlenselink] for the contribution +- Invalid byte sequences no longer throw iconv_strlen() errors (request #639) + - Thanks to [Willem Stuursma][@willemstuursma] for the patch +- Generic TodoSniff and FixmeSniff are now better at processing strings with invalid characters +- PEAR FunctionCallSignatureSniff now ignores indentation of inline HTML content +- Squiz ControlSignatureSniff now supports control structures with only inline HTML content + +### Fixed +- Fixed bug #636 : Some class names cause CSS tokenizer to hang +- Fixed bug #638 : VCS blame reports output error content from the blame commands for files not under VC +- Fixed bug #642 : Method params incorrectly detected when default value uses short array syntax + - Thanks to [Josh Davis][@joshdavis11] for the patch +- Fixed bug #644 : PEAR ScopeClosingBrace sniff does not work with mixed HTML/PHP +- Fixed bug #645 : FunctionSignature and ScopeIndent sniffs don't detect indents correctly when PHP open tag is not on a line by itself +- Fixed bug #648 : Namespace not tokenized correctly when followed by multiple use statements +- Fixed bug #654 : Comments affect indent check for BSDAllman brace style +- Fixed bug #658 : Squiz.Functions.FunctionDeclarationSpacing error for multi-line declarations with required spaces greater than zero + - Thanks to [J.D. Grimes][@JDGrimes] for the patch +- Fixed bug #663 : No space after class name generates: Class name "" is not in camel caps format +- Fixed bug #667 : Scope indent check can go into infinite loop due to some parse errors +- Fixed bug #670 : Endless loop in PSR1 SideEffects sniffer if no semicolon after last statement + - Thanks to [Thomas Jarosch][@thomasjfox] for the patch +- Fixed bug #672 : Call-time pass-by-reference false positive +- Fixed bug #683 : Comments are incorrectly reported by PSR2.ControlStructures.SwitchDeclaration sniff +- Fixed bug #687 : ScopeIndent does not check indent correctly for method prefixes like public and abstract +- Fixed bug #689 : False error on some comments after class closing brace + +## [2.3.3] - 2015-06-24 +### Changed +- Improved the performance of the CSS tokenizer, especially on very large CSS files (thousands of lines) + - Thanks to [Klaus Purer][@klausi] for the patch +- Defined tokens for lower PHP versions are now phpcs-specific strings instead of ints + - Stops conflict with other projects, like PHP_CodeCoverage +- Added more guard code for syntax errors to various sniffs +- Improved support for older HHVM versions + - Thanks to [Kunal Mehta][@legoktm] for the patch +- Squiz ValidLogicalOperatorsSniff now ignores XOR as type casting is different when using the ^ operator (request #567) +- Squiz CommentedOutCodeSniff is now better at ignoring URLs inside comments +- Squiz ControlSignatureSniff is now better at checking embedded PHP code +- Squiz ScopeClosingBraceSniff is now better at checking embedded PHP code + +### Fixed +- Fixed bug #584 : Squiz.Arrays.ArrayDeclaration sniff gives incorrect NoComma error for multiline string values +- Fixed bug #589 : PEAR.Functions.FunctionCallSignature sniff not checking all function calls +- Fixed bug #592 : USE statement tokenising can sometimes result in mismatched scopes +- Fixed bug #594 : Tokenizer issue on closure that returns by reference +- Fixed bug #595 : Colons in CSS selectors within media queries throw false positives + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #598 : PHPCBF can break function/use closure brace placement +- Fixed bug #603 : Squiz ControlSignatureSniff hard-codes opener type while fixing +- Fixed bug #605 : Auto report-width specified in ruleset.xml ignored +- Fixed bug #611 : Invalid numeric literal on CSS files under PHP7 +- Fixed bug #612 : Multi-file diff generating incorrectly if files do not end with EOL char +- Fixed bug #615 : Squiz OperatorBracketSniff incorrectly reports and fixes operations using self:: +- Fixed bug #616 : Squiz DisallowComparisonAssignmentSniff inconsistent errors with inline IF statements +- Fixed bug #617 : Space after switch keyword in PSR-2 is not being enforced +- Fixed bug #621 : PSR2 SwitchDeclaration sniff doesn't detect, or correctly fix, case body on same line as statement + +## [2.3.2] - 2015-04-29 +### Changed +- The error message for PSR2.ControlStructures.SwitchDeclaration.WrongOpenercase is now clearer (request #579) + +### Fixed +- Fixed bug #545 : Long list of CASE statements can cause tokenizer to reach a depth limit +- Fixed bug #565 : Squiz.WhiteSpace.OperatorSpacing reports negative number in short array + - Thanks to [Vašek Purchart][@VasekPurchart] for the patch + - Same fix also applied to Squiz.Formatting.OperatorBracket +- Fixed bug #569 : Generic ScopeIndentSniff throws PHP notices in JS files +- Fixed bug #570 : Phar class fatals in PHP less than 5.3 + +## [2.3.1] - 2015-04-23 +### Changed +- PHPCS can now exit with 0 even if errors are found + - Set the ignore_errors_on_exit config variable to 1 to set this behaviour + - Use with the ignore_warnings_on_exit config variable to never return a non-zero exit code +- Added Generic DisallowLongArraySyntaxSniff to enforce the use of the PHP short array syntax (request #483) + - Thanks to [Xaver Loppenstedt][@xalopp] for helping with tests +- Added Generic DisallowShortArraySyntaxSniff to ban the use of the PHP short array syntax (request #483) + - Thanks to [Xaver Loppenstedt][@xalopp] for helping with tests +- Generic ScopeIndentSniff no longer does exact checking for content inside parenthesis (request #528) + - Only applies to custom coding standards that set the "exact" flag to TRUE +- Squiz ConcatenationSpacingSniff now has a setting to ignore newline characters around operators (request #511) + - Default remains FALSE, so newlines are not allowed + - Override the "ignoreNewlines" setting in a ruleset.xml file to change +- Squiz InlineCommentSniff no longer checks the last char of a comment if the first char is not a letter (request #505) +- The Squiz standard has increased the max padding for statement alignment from 12 to 20 + +### Fixed +- Fixed bug #479 : Yielded values are not recognised as returned values in Squiz FunctionComment sniff +- Fixed bug #512 : Endless loop whilst parsing mixture of control structure styles +- Fixed bug #515 : Spaces in JS block incorrectly flagged as indentation error +- Fixed bug #523 : Generic ScopeIndent errors for IF in FINALLY +- Fixed bug #527 : Closure inside IF statement is not tokenized correctly +- Fixed bug #529 : Squiz.Strings.EchoedStrings gives false positive when echo'ing using an inline condition +- Fixed bug #537 : Using --config-set is breaking phpcs.phar +- Fixed bug #543 : SWITCH with closure in condition generates inline control structure error +- Fixed bug #551 : Multiple catch blocks not checked in Squiz.ControlStructures.ControlSignature sniff +- Fixed bug #554 : ScopeIndentSniff causes errors when encountering an unmatched parenthesis +- Fixed bug #558 : PHPCBF adds brace for ELSE IF split over multiple lines +- Fixed bug #564 : Generic MultipleStatementAlignment sniff reports incorrect errors for multiple assignments on a single line + +## [2.3.0] - 2015-03-04 +### Changed +- The existence of the main config file is now cached to reduce is_file() calls when it doesn't exist (request #486) +- Abstract classes inside the Sniffs directory are now ignored even if they are named [Name]Sniff.php (request #476) + - Thanks to [David Vernet][@Decave] for the patch +- PEAR and Squiz FileComment sniffs no longer have @ in their error codes + - e.g., PEAR.Commenting.FileComment.Duplicate@categoryTag becomes PEAR.Commenting.FileComment.DuplicateCategoryTag + - e.g., Squiz.Commenting.FileComment.Missing@categoryTag becomes Squiz.Commenting.FileComment.MissingCategoryTag +- PEAR MultiLineConditionSniff now allows comment lines inside multi-line IF statement conditions + - Thanks to [Klaus Purer][@klausi] for the patch +- Generic ForbiddenFunctionsSniff now supports setting null replacements in ruleset files (request #263) +- Generic opening function brace sniffs now support checking of closures + - Set the checkClosures property to TRUE (default is FALSE) in your ruleset.xml file to enable this + - Can also set the checkFunctions property to FALSE (default is TRUE) in your ruleset.xml file to only check closures + - Affects OpeningFunctionBraceBsdAllmanSniff and OpeningFunctionBraceKernighanRitchieSniff +- Generic OpeningFunctionBraceKernighanRitchieSniff can now fix all the errors it finds +- Generic OpeningFunctionBraceKernighanRitchieSniff now allows empty functions with braces next to each other +- Generic OpeningFunctionBraceBsdAllmanSniff now allows empty functions with braces next to each other +- Improved auto report width for the "full" report +- Improved conflict detection during auto fixing +- Generic ScopeIndentSniff is no longer confused by empty closures +- Squiz ControlSignatureSniff now always ignores comments (fixes bug #490) + - Include the Squiz.Commenting.PostStatementComment sniff in your ruleset.xml to ban these comments again +- Squiz OperatorSpacingSniff no longer throws errors for code in the form ($foo || -1 === $bar) +- Fixed errors tokenizing T_ELSEIF tokens on HHVM 3.5 +- Squiz ArrayDeclarationSniff is no longer tricked by comments after array values +- PEAR IncludingFileSniff no longer produces invalid code when removing parenthesis from require/include statements + +### Fixed +- Fixed bug #415 : The @codingStandardsIgnoreStart has no effect during fixing +- Fixed bug #432 : Properties of custom sniffs cannot be configured +- Fixed bug #453 : PSR2 standard does not allow closing tag for mixed PHP/HTML files +- Fixed bug #457 : FunctionCallSignature sniffs do not support here/nowdoc syntax and can cause syntax error when fixing +- Fixed bug #466 : PropertyLabelSpacing JS fixer issue when there is no space after colon +- Fixed bug #473 : Writing a report for an empty folder to existing file includes the existing contents +- Fixed bug #485 : PHP notice in Squiz.Commenting.FunctionComment when checking malformed @throws comment +- Fixed bug #491 : Generic InlineControlStructureSniff can correct with missing semicolon + - Thanks to [Jesse Donat][@donatj] for the patch +- Fixed bug #492 : Use statements don't increase the scope indent +- Fixed bug #493 : PSR1_Sniffs_Methods_CamelCapsMethodNameSniff false positives for some magic method detection + - Thanks to [Andreas Möller][@localheinz] for the patch +- Fixed bug #496 : Closures in PSR2 are not checked for a space after the function keyword +- Fixed bug #497 : Generic InlineControlStructureSniff does not support alternative SWITCH syntax +- Fixed bug #500 : Functions not supported as values in Squiz ArrayDeclaration sniff +- Fixed bug #501 : ScopeClosingBrace and ScopeIndent conflict with closures used as array values + - Generic ScopeIndentSniff may now report fewer errors for closures, but perform the same fixes +- Fixed bug #502 : PSR1 SideEffectsSniff sees declare() statements as side effects + +## [2.2.0] - 2015-01-22 +### Changed +- Added (hopefully) tastefully used colors to report and progress output for the phpcs command + - Use the --colors command line argument to use colors in output + - Use the command "phpcs --config-set colors true" to turn colors on by default + - Use the --no-colors command line argument to turn colors off when the config value is set +- Added support for using the full terminal width for report output + - Use the --report-width=auto command line argument to auto-size the reports + - Use the command "phpcs --config-set report_width auto" to use auto-sizing by default +- Reports will now size to fit inside the report width setting instead of always using padding to fill the space +- If no files or standards are specified, PHPCS will now look for a phpcs.xml file in the current directory + - This file has the same format as a standard ruleset.xml file + - The phpcs.xml file should specify (at least) files to process and a standard/sniffs to use + - Useful for running the phpcs and phpcbf commands without any arguments at the top of a repository +- Default file paths can now be specified in a ruleset.xml file using the "file" tag + - File paths are only processed if no files were specified on the command line +- Extensions specified on the CLI are now merged with those set in ruleset.xml files + - Previously, the ruleset.xml file setting replaced the CLI setting completely +- Squiz coding standard now requires lowercase PHP constants (true, false and null) + - Removed Squiz.NamingConventions.ConstantCase sniff as the rule is now consistent across PHP and JS files +- Squiz FunctionOpeningBraceSpaceSniff no longer does additional checks for JS functions + - PHP and JS functions and closures are now treated the same way +- Squiz MultiLineFunctionDeclarationSniff now supports JS files +- Interactive mode no longer breaks if you also specify a report type on the command line +- PEAR InlineCommentSniff now fixes the Perl-style comments that it finds (request #375) +- PSR2 standard no longer fixes the placement of docblock open tags as comments are excluded from this standard +- PSR2 standard now sets a default tab width of 4 spaces +- Generic DocCommentSniff now only disallows lowercase letters at the start of a long/short comment (request #377) + - All non-letter characters are now allowed, including markdown special characters and numbers +- Generic DisallowMultipleStatementsSniff now allows multiple open/close tags on the same line (request #423) +- Generic CharacterBeforePHPOpeningTagSniff now only checks the first PHP tag it finds (request #423) +- Generic CharacterBeforePHPOpeningTagSniff now allows a shebang line at the start of the file (request #20481) +- Generic InlineHTMLUnitTest now allows a shebang line at the start of the file (request #20481) +- PEAR ObjectOperatorIndentSniff now only checks object operators at the start of a line +- PEAR FileComment and ClassComment sniffs no longer have @ in their error codes + - E.g., PEAR.Commenting.FileComment.Missing@categoryTag becomes PEAR.Commenting.FileComment.MissingCategoryTag + - Thanks to [Grzegorz Rygielski][@grzr] for the patch +- Squiz ControlStructureSpacingSniff no longer enforces a blank line before CATCH statements +- Squiz FunctionCommentSniff now fixes the return type in the @return tag (request #392) +- Squiz BlockCommentSniff now only disallows lowercase letters at the start of the comment +- Squiz InlineCommentSniff now only disallows lowercase letters at the start of the comment +- Squiz OperatorSpacingSniff now has a setting to ignore newline characters around operators (request #348) + - Default remains FALSE, so newlines are not allowed + - Override the "ignoreNewlines" setting in a ruleset.xml file to change +- PSR2 ControlStructureSpacingSniff now checks for, and fixes, newlines after the opening parenthesis +- Added a markdown document generator (--generator=markdown to use) + - Thanks to [Stefano Kowalke][@Konafets] for the contribution + +### Fixed +- Fixed bug #379 : Squiz.Arrays.ArrayDeclaration.NoCommaAfterLast incorrectly detects comments +- Fixed bug #382 : JS tokenizer incorrect for inline conditionally created immediately invoked anon function +- Fixed bug #383 : Squiz.Arrays.ArrayDeclaration.ValueNoNewline incorrectly detects nested arrays +- Fixed bug #386 : Undefined offset in Squiz.FunctionComment sniff when param has no comment +- Fixed bug #390 : Indentation of non-control structures isn't adjusted when containing structure is fixed +- Fixed bug #400 : InlineControlStructureSniff fails to fix when statement has no semicolon +- Fixed bug #401 : PHPCBF no-patch option shows an error when there are no fixable violations in a file +- Fixed bug #405 : The "Squiz.WhiteSpace.FunctionSpacing" sniff removes class "}" during fixing +- Fixed bug #407 : PEAR.ControlStructures.MultiLineCondition doesn't account for comments at the end of lines +- Fixed bug #410 : The "Squiz.WhiteSpace.MemberVarSpacing" not respecting "var" +- Fixed bug #411 : Generic.WhiteSpace.ScopeIndent.Incorrect - false positive with multiple arrays in argument list +- Fixed bug #412 : PSR2 multi-line detection doesn't work for inline IF and string concats +- Fixed bug #414 : Squiz.WhiteSpace.MemberVarSpacing - inconsistent checking of member vars with comment +- Fixed bug #433 : Wrong detection of Squiz.Arrays.ArrayDeclaration.KeyNotAligned when key contains space +- Fixed bug #434 : False positive for spacing around "=>" in inline array within foreach +- Fixed bug #452 : Ruleset exclude-pattern for specific sniff code ignored when using CLI --ignore option +- Fixed bug #20482 : Scope indent sniff can get into infinite loop when processing a parse error + +## [2.1.0] - 2014-12-18 +### Changed +- Time and memory output is now shown if progress information is also shown (request #335) +- A tilde can now be used to reference a user's home directory in a path to a standard (request #353) +- Added PHP_CodeSniffer_File::findStartOfStatement() to find the first non-whitespace token in a statement + - Possible alternative for code using PHP_CodeSniffer_File::findPrevious() with the local flag set +- Added PHP_CodeSniffer_File::findEndOfStatement() to find the last non-whitespace token in a statement + - Possible alternative for code using PHP_CodeSniffer_File::findNext() with the local flag set +- Generic opening function brace sniffs now ensure the opening brace is the last content on the line + - Affects OpeningFunctionBraceBsdAllmanSniff and OpeningFunctionBraceKernighanRitchieSniff + - Also enforced in PEAR FunctionDeclarationSniff and Squiz MultiLineFunctionDeclarationSniff +- Generic DisallowTabIndentSniff now replaces tabs everywhere it finds them, except in strings and here/now docs +- Generic EmptyStatementSniff error codes now contain the type of empty statement detected (request #314) + - All messages generated by this sniff are now errors (empty CATCH was previously a warning) + - Message code Generic.CodeAnalysis.EmptyStatement.NotAllowed has been removed + - Message code Generic.CodeAnalysis.EmptyStatement.NotAllowedWarning has been removed + - New message codes have the format Generic.CodeAnalysis.EmptyStatement.Detected[TYPE] + - Example code is Generic.CodeAnalysis.EmptyStatement.DetectedCATCH + - You can now use a custom ruleset to change messages to warnings and to exclude them +- PEAR and Squiz FunctionCommentSniffs no longer ban @return tags for constructors and destructors + - Removed message PEAR.Commenting.FunctionComment.ReturnNotRequired + - Removed message Squiz.Commenting.FunctionComment.ReturnNotRequired + - Change initiated by request #324 and request #369 +- Squiz EmptyStatementSniff has been removed + - Squiz standard now includes Generic EmptyStatementSniff and turns off the empty CATCH error +- Squiz ControlSignatureSniff fixes now retain comments between the closing parenthesis and open brace +- Squiz SuperfluousWhitespaceSniff now checks for extra blank lines inside closures + - Thanks to [Sertan Danis][@sertand] for the patch +- Squiz ArrayDeclarationSniff now skips function calls while checking multi-line arrays + +### Fixed +- Fixed bug #337 : False positive with anonymous functions in Generic_Sniffs_WhiteSpace_ScopeIndentSniff +- Fixed bug #339 : reformatting brace location can result in broken code +- Fixed bug #342 : Nested ternary operators not tokenized correctly +- Fixed bug #345 : Javascript regex not tokenized when inside array +- Fixed bug #346 : PHP path can't be determined in some cases in "phpcs.bat" (on Windows XP) +- Fixed bug #358 : False positives for Generic_Sniffs_WhiteSpace_ScopeIndentSniff +- Fixed bug #361 : Sniff-specific exclude patterns don't work for Windows +- Fixed bug #364 : Don't interpret "use function" as declaration +- Fixed bug #366 : phpcbf with PSR2 errors on control structure alternative syntax +- Fixed bug #367 : Nested Anonymous Functions Causing False Negative +- Fixed bug #371 : Shorthand binary cast causes tokenizer errors + - New token T_BINARY_CAST added for the b"string" cast format (the 'b' is the T_BINARY_CAST token) +- Fixed bug #372 : phpcbf parse problem, wrong brace placement for inline IF +- Fixed bug #373 : Double quote usage fix removing too many double quotes +- Fixed bug #20196 : 1.5.2 breaks scope_closer position + +## [2.0.0] - 2014-12-05 +### Changed +- JS tokenizer now sets functions as T_CLOSUREs if the function is anonymous +- JS tokenizer now sets all objects to T_OBJECT + - Object end braces are set to a new token T_CLOSE_OBJECT + - T_OBJECT tokens no longer act like scopes; i.e., they have no condition/opener/closer + - T_PROPERTY tokens no longer act like scopes; i.e., they have no condition/opener/closer + - T_OBJECT tokens have a bracket_closer instead, which can be used to find the ending + - T_CLOSE_OBJECT tokens have a bracket_opener +- Improved regular expression detection in the JS tokenizer +- You can now get PHP_CodeSniffer to ignore a single line by putting @codingStandardsIgnoreLine in a comment + - When the comment is found, the comment line and the following line will be ignored + - Thanks to [Andy Bulford][@abulford] for the contribution +- PHPCBF now prints output when it is changing into directories +- Improved conflict detection during auto fixing +- The -vvv command line argument will now output the current file content for each loop during fixing +- Generic ScopeIndentSniff now checks that open/close PHP tags are aligned to the correct column +- PEAR FunctionCallSignatureSniff now checks indent of closing parenthesis even if it is not on a line by itself +- PEAR FunctionCallSignatureSniff now supports JS files +- PEAR MultiLineConditionSniff now supports JS files +- Squiz DocCommentAlignmentSniff now supports JS files +- Fixed a problem correcting the closing brace line in Squiz ArrayDeclarationSniff +- Fixed a problem auto-fixing the Squiz.WhiteSpace.FunctionClosingBraceSpace.SpacingBeforeNestedClose error +- Squiz EmbeddedPhpSniff no longer reports incorrect alignment of tags when they are not on new lines +- Squiz EmbeddedPhpSniff now aligns open tags correctly when moving them onto a new line +- Improved fixing of arrays with multiple values in Squiz ArrayDeclarationSniff +- Improved detection of function comments in Squiz FunctionCommentSpacingSniff +- Improved fixing of lines after cases statements in Squiz SwitchDeclarationSniff + +### Fixed +- Fixed bug #311 : Suppression of function prototype breaks checking of lines within function +- Fixed bug #320 : Code sniffer indentation issue +- Fixed bug #333 : Nested ternary operators causing problems + +## [1.5.6] - 2014-12-05 +### Changed +- JS tokenizer now detects xor statements correctly +- The --config-show command now pretty-prints the config values + - Thanks to [Ken Guest][@kenguest] for the patch +- Setting and removing config values now catches exceptions if the config file is not writable + - Thanks to [Ken Guest][@kenguest] for the patch +- Setting and removing config values now prints a message to confirm the action and show old values +- You can now get PHP_CodeSniffer to ignore a single line by putting @codingStandardsIgnoreLine in a comment + - When the comment is found, the comment line and the following line will be ignored + - Thanks to [Andy Bulford][@abulford] for the contribution +- Generic ConstructorNameSniff no longer errors for PHP4 style constructors when __construct() is present + - Thanks to [Thibaud Fabre][@fabre-thibaud] for the patch + +### Fixed +- Fixed bug #280 : The --config-show option generates error when there is no config file +- Fixed bug #306 : File containing only a namespace declaration raises undefined index notice +- Fixed bug #308 : Squiz InlineIfDeclarationSniff fails on ternary operators inside closure +- Fixed bug #310 : Variadics not recognized by tokenizer +- Fixed bug #311 : Suppression of function prototype breaks checking of lines within function + +## [2.0.0RC4] - 2014-11-07 +### Changed +- JS tokenizer now detects xor statements correctly +- Improved detection of properties and objects in the JS tokenizer +- Generic ScopeIndentSniff can now fix indents using tabs instead of spaces + - Set the tabIndent property to TRUE in your ruleset.xml file to enable this + - It is important to also set a tab-width setting, either in the ruleset or on the command line, for accuracy +- Generic ScopeIndentSniff now checks and auto-fixes JS files +- Generic DisallowSpaceIndentSniff is now able to replace space indents with tab indents during fixing +- Support for phpcs-only and phpcbf-only attributes has been added to all ruleset.xml elements + - Allows parts of the ruleset to only apply when using a specific tool + - Useful for doing things like excluding indent fixes but still reporting indent errors +- Unit tests can now set command line arguments during a test run + - Override getCliValues() and pass an array of CLI arguments for each file being tested +- File-wide sniff properties can now be set using T_INLINE_HTML content during unit test runs + - Sniffs that start checking at the open tag can only, normally, have properties set using a ruleset +- Generic ConstructorNameSniff no longer errors for PHP4 style constructors when __construct() is present + - Thanks to [Thibaud Fabre][@fabre-thibaud] for the patch +- Generic DocCommentSniff now checks that the end comment tag is on a new line +- Generic MultipleStatementAlignmentSniff no longer skips assignments for closures +- Squiz DocCommentAlignment sniff now has better checking for single line doc block +- Running unit tests with the -v CLI argument no longer generates PHP errors + +### Fixed +- Fixed bug #295 : ScopeIndentSniff hangs when processing nested closures +- Fixed bug #298 : False positive in ScopeIndentSniff when anonymous functions are used with method chaining +- Fixed bug #302 : Fixing code in Squiz InlineComment sniff can remove some comment text +- Fixed bug #303 : Open and close tag on same line can cause a PHP notice checking scope indent +- Fixed bug #306 : File containing only a namespace declaration raises undefined index notice +- Fixed bug #307 : Conditional breaks in case statements get incorrect indentations +- Fixed bug #308 : Squiz InlineIfDeclarationSniff fails on ternary operators inside closure +- Fixed bug #310 : Variadics not recognized by tokenizer + +## [2.0.0RC3] - 2014-10-16 +### Changed +- Improved default output for PHPCBF and removed the options to print verbose and progress output +- If a .fixed file is supplied for a unit test file, the auto fixes will be checked against it during testing + - See Generic ScopeIndentUnitTest.inc and ScopeIndentUnitTest.inc.fixed for an example +- Fixer token replacement methods now return TRUE if the change was accepted and FALSE if rejected +- The --config-show command now pretty-prints the config values + - Thanks to [Ken Guest][@kenguest] for the patch +- Setting and removing config values now catches exceptions if the config file is not writable + - Thanks to [Ken Guest][@kenguest] for the patch +- Setting and removing config values now prints a message to confirm the action and show old values +- Generic ScopeIndentSniff has been completely rewritten to improve fixing and embedded PHP detection +- Generic DisallowTabIndent and DisallowSpaceIndent sniffs now detect indents at the start of block comments +- Generic DisallowTabIndent and DisallowSpaceIndent sniffs now detect indents inside multi-line strings +- Generic DisallowTabIndentSniff now replaces tabs inside doc block comments +- Squiz ControlStructureSpacingSniff error codes have been corrected; they were reversed +- Squiz EmbeddedPhpSniff now checks open and close tag indents and fixes some errors +- Squiz FileCommentSniff no longer throws incorrect blank line before comment errors in JS files +- Squiz ClassDeclarationSniff now has better checking for blank lines after a closing brace +- Removed error Squiz.Classes.ClassDeclaration.NoNewlineAfterCloseBrace (request #285) + - Already handled by Squiz.Classes.ClassDeclaration.CloseBraceSameLine + +### Fixed +- Fixed bug #280 : The --config-show option generates error when there is no config file + +## [2.0.0RC2] - 2014-09-26 +### Changed +- Minified JS and CSS files are now detected and skipped (fixes bug #252 and bug #19899) + - A warning will be added to the file so it can be found in the report and ignored in the future +- Fixed incorrect length of JS object operator tokens +- PHP tokenizer no longer converts class/function names to special tokens types + - Class/function names such as parent and true would become special tokens such as T_PARENT and T_TRUE +- PHPCS can now exit with 0 if only warnings were found (request #262) + - Set the ignore_warnings_on_exit config variable to 1 to set this behaviour + - Default remains at exiting with 0 only if no errors and no warnings were found + - Also changes return value of PHP_CodeSniffer_Reporting::printReport() +- Rulesets can now set associative array properties + - property name="[property]" type="array" value="foo=>bar,baz=>qux" +- Generic ForbiddenFunctionsSniff now has a public property called forbiddenFunctions (request #263) + - Override the property in a ruleset.xml file to define forbidden functions and their replacements + - A replacement of NULL indicates that no replacement is available + - e.g., value="delete=>unset,print=>echo,create_function=>null" + - Custom sniffs overriding this one will need to change the visibility of their member var +- Improved closure support in Generic ScopeIndentSniff +- Improved indented PHP tag support in Generic ScopeIndentSniff +- Improved fixing of mixed line indents in Generic ScopeIndentSniff +- Added conflict detection to the file fixer + - If 2 sniffs look to be conflicting, one change will be ignored to allow a fix to occur +- Generic CamelCapsFunctionNameSniff now ignores a single leading underscore + - Thanks to [Alex Slobodiskiy][@xt99] for the patch +- Standards can now be located within hidden directories (further fix for bug #20323) + - Thanks to [Klaus Purer][@klausi] for the patch +- Sniff ignore patterns now replace Win dir separators like file ignore patterns already did +- Exclude patterns now use backtick delimiters, allowing all special characters to work correctly again + - Thanks to [Jeremy Edgell][@jedgell] for the patch +- Errors converted to warnings in a ruleset (and vice versa) now retain their fixable status + - Thanks to [Alexander Obuhovich][@aik099] for the patch +- Squiz ConcatenationSpacingSniff now has a setting to specify how many spaces there should around concat operators + - Default remains at 0 + - Override the "spacing" setting in a ruleset.xml file to change +- Added auto-fixes for Squiz InlineCommentSniff +- Generic DocCommentSniff now correctly fixes additional blank lines at the end of a comment +- Squiz OperatorBracketSniff now correctly fixes operations that include arrays +- Zend ClosingTagSniff fix now correctly leaves closing tags when followed by HTML +- Added Generic SyntaxSniff to check for syntax errors in PHP files + - Thanks to [Blaine Schmeisser][@bayleedev] for the contribution +- Added Generic OneTraitPerFileSniff to check that only one trait is defined in each file + - Thanks to [Alexander Obuhovich][@aik099] for the contribution +- Squiz DiscouragedFunctionsSniff now warns about var_dump() +- PEAR ValidFunctionNameSniff no longer throws an error for _() +- Squiz and PEAR FunctionCommentSniffs now support _() +- Generic DisallowTabIndentSniff now checks for, and fixes, mixed indents again +- Generic UpperCaseConstantSniff and LowerCaseConstantSniff now ignore function names + +### Fixed +- Fixed bug #243 : Missing DocBlock not detected +- Fixed bug #248 : FunctionCommentSniff expects ampersand on param name +- Fixed bug #265 : False positives with type hints in ForbiddenFunctionsSniff +- Fixed bug #20373 : Inline comment sniff tab handling way +- Fixed bug #20377 : Error when trying to execute phpcs with report=json +- Fixed bug #20378 : Report appended to existing file if no errors found in run +- Fixed bug #20381 : Invalid "Comment closer must be on a new line" + - Thanks to [Brad Kent][@bkdotcom] for the patch +- Fixed bug #20402 : SVN pre-commit hook fails due to unknown argument error + +## [1.5.5] - 2014-09-25 +### Changed +- PHP tokenizer no longer converts class/function names to special tokens types + - Class/function names such as parent and true would become special tokens such as T_PARENT and T_TRUE +- Improved closure support in Generic ScopeIndentSniff +- Improved indented PHP tag support in Generic ScopeIndentSniff +- Generic CamelCapsFunctionNameSniff now ignores a single leading underscore + - Thanks to [Alex Slobodiskiy][@xt99] for the patch +- Standards can now be located within hidden directories (further fix for bug #20323) + - Thanks to [Klaus Purer][@klausi] for the patch +- Added Generic SyntaxSniff to check for syntax errors in PHP files + - Thanks to [Blaine Schmeisser][@bayleedev] for the contribution +- Squiz DiscouragedFunctionsSniff now warns about var_dump() +- PEAR ValidFunctionNameSniff no longer throws an error for _() +- Squiz and PEAR FunctionCommentSnif now support _() +- Generic UpperCaseConstantSniff and LowerCaseConstantSniff now ignore function names + +### Fixed +- Fixed bug #248 : FunctionCommentSniff expects ampersand on param name +- Fixed bug #265 : False positives with type hints in ForbiddenFunctionsSniff +- Fixed bug #20373 : Inline comment sniff tab handling way +- Fixed bug #20378 : Report appended to existing file if no errors found in run +- Fixed bug #20381 : Invalid "Comment closer must be on a new line" + - Thanks to [Brad Kent][@bkdotcom] for the patch +- Fixed bug #20386 : Squiz.Commenting.ClassComment.SpacingBefore thrown if first block comment + +## [2.0.0RC1] - 2014-08-06 +### Changed +- PHPCBF will now fix incorrect newline characters in a file +- PHPCBF now exists cleanly when there are no errors to fix +- Added phpcbf.bat file for Windows +- Verbose option no longer errors when using a phar file with a space in the path +- Fixed a reporting error when using HHVM + - Thanks to [Martins Sipenko][@martinssipenko] for the patch +- addFixableError() and addFixableWarning() now only return true if the fixer is enabled + - Saves checking ($phpcsFile->fixer->enabled === true) before every fix +- Added addErrorOnLine() and addWarningOnLine() to add a non-fixable violation to a line at column 1 + - Useful if you are generating errors using an external tool or parser and only know line numbers + - Thanks to [Ondřej Mirtes][@ondrejmirtes] for the patch +- CSS tokenizer now identifies embedded PHP code using the new T_EMBEDDED_PHP token type + - The entire string of PHP is contained in a single token +- PHP tokenizer contains better detection of short array syntax +- Unit test runner now also test any standards installed under the installed_paths config var +- Exclude patterns now use {} delimiters, allowing the | special character to work correctly again +- The filtering component of the --extensions argument is now ignored again when passing filenames + - Can still be used to specify a custom tokenizer for each extension when passing filenames + - If no tokenizer is specified, default values will be used for common file extensions +- Diff report now produces relative paths on Windows, where possible (further fix for bug #20234) +- If a token's content has been modified by the tab-width setting, it will now have an orig_content in the tokens array +- Generic DisallowSpaceIndent and DisallowTabIndent sniffs now check original indent content even when tab-width is set + - Previously, setting --tab-width would force both to check the indent as spaces +- Fixed a problem where PHPCBF could replace tabs with too many spaces when changing indents +- Fixed a problem that could occur with line numbers when using HHVM to check files with Windows newline characters +- Removed use of sys_get_temp_dir() as this is not supported by the min PHP version +- Squiz ArrayDeclarationSniff now supports short array syntax +- Squiz ControlSignatureSniff no longer uses the Abstract Pattern sniff + - If you are extending this sniff, you'll need to rewrite your code + - The rewrite allows this sniff to fix all control structure formatting issues it finds +- The installed_paths config var now accepts relative paths + - The paths are relative to the PHP_CodeSniffer install directory + - Thanks to [Weston Ruter][@westonruter] for the patch +- Generic ScopeIndentSniff now accounts for different open tag indents +- PEAR FunctionDeclarationSniff now ignores short arrays when checking indent + - Thanks to [Daniel Tschinder][@danez] for the patch +- PSR2 FunctionCallSignatureSniff now treats multi-line strings as a single-line argument, like arrays and closures + - Thanks to [Dawid Nowak][@MacDada] for the patch +- PSR2 UseDeclarationSniff now checks for a single space after the USE keyword +- Generic ForbiddenFunctionsSniff now detects calls to functions in the global namespace + - Thanks to [Ole Martin Handeland][@olemartinorg] for the patch +- Generic LowerCaseConstantSniff and UpperCaseConstantSniff now ignore namespaces beginning with TRUE/FALSE/NULL + - Thanks to [Renan Gonçalves][@renan] for the patch +- Squiz InlineCommentSniff no longer requires a blank line after post-statement comments (request #20299) +- Squiz SelfMemberReferenceSniff now works correctly with namespaces +- Squiz FunctionCommentSniff is now more relaxed when checking namespaced type hints +- Tab characters are now encoded in abstract pattern errors messages + - Thanks to [Blaine Schmeisser][@bayleedev] for the patch +- Invalid sniff codes passed to --sniffs now show a friendly error message (request #20313) +- Generic LineLengthSniff now shows a warning if the iconv module is disabled (request #20314) +- Source report no longer shows errors if category or sniff names ends in an uppercase error + - Thanks to [Jonathan Marcil][@jmarcil] for the patch + +### Fixed +- Fixed bug #20261 : phpcbf has an endless fixing loop +- Fixed bug #20268 : Incorrect documentation titles in PEAR documentation +- Fixed bug #20296 : new array notion in function comma check fails +- Fixed bug #20297 : phar does not work when renamed it to phpcs +- Fixed bug #20307 : PHP_CodeSniffer_Standards_AbstractVariableSniff analyze traits +- Fixed bug #20308 : Squiz.ValidVariableNameSniff - wrong variable usage +- Fixed bug #20309 : Use "member variable" term in sniff "processMemberVar" method +- Fixed bug #20310 : PSR2 does not check for space after function name +- Fixed bug #20322 : Display rules set to type=error even when suppressing warnings +- Fixed bug #20323 : PHPCS tries to load sniffs from hidden directories +- Fixed bug #20346 : Fixer endless loop with Squiz.CSS sniffs +- Fixed bug #20355 : No sniffs are registered with PHAR on Windows + +## [1.5.4] - 2014-08-06 +### Changed +- Removed use of sys_get_temp_dir() as this is not supported by the min PHP version +- The installed_paths config var now accepts relative paths + - The paths are relative to the PHP_CodeSniffer install directory + - Thanks to [Weston Ruter][@westonruter] for the patch +- Generic ScopeIndentSniff now accounts for different open tag indents +- PEAR FunctionDeclarationSniff now ignores short arrays when checking indent + - Thanks to [Daniel Tschinder][@danez] for the patch +- PSR2 FunctionCallSignatureSniff now treats multi-line strings as a single-line argument, like arrays and closures + - Thanks to [Dawid Nowak][@MacDada] for the patch +- Generic ForbiddenFunctionsSniff now detects calls to functions in the global namespace + - Thanks to [Ole Martin Handeland][@olemartinorg] for the patch +- Generic LowerCaseConstantSniff and UpperCaseConstantSniff now ignore namespaces beginning with TRUE/FALSE/NULL + - Thanks to [Renan Gonçalves][@renan] for the patch +- Squiz InlineCommentSniff no longer requires a blank line after post-statement comments (request #20299) +- Squiz SelfMemberReferenceSniff now works correctly with namespaces +- Tab characters are now encoded in abstract pattern errors messages + - Thanks to [Blaine Schmeisser][@bayleedev] for the patch +- Invalid sniff codes passed to --sniffs now show a friendly error message (request #20313) +- Generic LineLengthSniff now shows a warning if the iconv module is disabled (request #20314) +- Source report no longer shows errors if category or sniff names ends in an uppercase error + - Thanks to [Jonathan Marcil][@jmarcil] for the patch + +### Fixed +- Fixed bug #20268 : Incorrect documentation titles in PEAR documentation +- Fixed bug #20296 : new array notion in function comma check fails +- Fixed bug #20307 : PHP_CodeSniffer_Standards_AbstractVariableSniff analyze traits +- Fixed bug #20308 : Squiz.ValidVariableNameSniff - wrong variable usage +- Fixed bug #20309 : Use "member variable" term in sniff "processMemberVar" method +- Fixed bug #20310 : PSR2 does not check for space after function name +- Fixed bug #20322 : Display rules set to type=error even when suppressing warnings +- Fixed bug #20323 : PHPCS tries to load sniffs from hidden directories + +## [2.0.0a2] - 2014-05-01 +### Changed +- Added report type --report=info to show information about the checked code to make building a standard easier + - Checks a number of things, such as what line length you use, and spacing are brackets, but not everything + - Still highly experimental +- Generic LineLengthSniff now shows warnings for long lines referring to licence and VCS information + - It previously ignored these lines, but at the expense of performance +- Generic DisallowTabIndent and DisallowSpaceIndent sniffs no longer error when detecting mixed indent types + - Only the first type of indent found on a line (space or indent) is considered +- Lots of little performance improvements that can add up to a substantial saving over large code bases + - Added a "length" array index to tokens so you don't need to call strlen() of them, or deal with encoding + - Can now use isset() to find tokens inside the PHP_CodeSniffer_Tokens static vars instead of in_array() +- Custom reports can now specify a $recordErrors member var; this previously only worked for built-in reports + - When set to FALSE, error messages will not be recorded and only totals will be returned + - This can save significant memory while processing a large code base +- Removed dependence on PHP_Timer +- PHP tokenizer now supports DEFAULT statements opened with a T_SEMICOLON +- The Squiz and PHPCS standards have increased the max padding for statement alignment from 8 to 12 +- Squiz EchoedStringsSniff now supports statements without a semicolon, such as PHP embedded in HTML +- Squiz DoubleQuoteUsageSniff now properly replaces escaped double quotes when fixing a doubled quoted string +- Improved detection of nested IF statements that use the alternate IF/ENDIF syntax +- PSR1 CamelCapsMethodNameSniff now ignores magic methods + - Thanks to [Eser Ozvataf][@eser] for the patch +- PSR1 SideEffectsSniff now ignores methods named define() +- PSR1 and PEAR ClassDeclarationSniffs now support traits (request #20208) +- PSR2 ControlStructureSpacingSniff now allows newlines before/after parentheses + - Thanks to [Maurus Cuelenaere][@mcuelenaere] for the patch +- PSR2 ControlStructureSpacingSniff now checks TRY and CATCH statements +- Squiz SuperfluousWhitespaceSniff now detects whitespace at the end of block comment lines + - Thanks to [Klaus Purer][@klausi] for the patch +- Squiz LowercasePHPFunctionsSniff no longer reports errors for namespaced functions + - Thanks to [Max Galbusera][@maxgalbu] for the patch +- Squiz SwitchDeclarationSniff now allows exit() as a breaking statement for case/default +- Squiz ValidVariableNameSniff and Zend ValidVariableNameSniff now ignore additional PHP reserved vars + - Thanks to Mikuláš Dítě and Adrian Crepaz for the patch +- Sniff code Squiz.WhiteSpace.MemberVarSpacing.After changed to Squiz.WhiteSpace.MemberVarSpacing.Incorrect (request #20241) + +### Fixed +- Fixed bug #20200 : Invalid JSON produced with specific error message +- Fixed bug #20204 : Ruleset exclude checks are case sensitive +- Fixed bug #20213 : Invalid error, Inline IF must be declared on single line +- Fixed bug #20225 : array_merge() that takes more than one line generates error +- Fixed bug #20230 : Squiz ControlStructureSpacing sniff assumes specific condition formatting +- Fixed bug #20234 : phpcbf patch command absolute paths +- Fixed bug #20240 : Squiz block comment sniff fails when newline present +- Fixed bug #20247 : The Squiz.WhiteSpace.ControlStructureSpacing sniff and do-while + - Thanks to [Alexander Obuhovich][@aik099] for the patch +- Fixed bug #20248 : The Squiz_Sniffs_WhiteSpace_ControlStructureSpacingSniff sniff and empty scope +- Fixed bug #20252 : Unitialized string offset when package name starts with underscore + +## [1.5.3] - 2014-05-01 +### Changed +- Improved detection of nested IF statements that use the alternate IF/ENDIF syntax +- PHP tokenizer now supports DEFAULT statements opened with a T_SEMICOLON +- PSR1 CamelCapsMethodNameSniff now ignores magic methods + - Thanks to [Eser Ozvataf][@eser] for the patch +- PSR1 SideEffectsSniff now ignores methods named define() +- PSR1 and PEAR ClassDeclarationSniffs now support traits (request #20208) +- PSR2 ControlStructureSpacingSniff now allows newlines before/after parentheses + - Thanks to [Maurus Cuelenaere][@mcuelenaere] for the patch +- Squiz LowercasePHPFunctionsSniff no longer reports errors for namespaced functions + - Thanks to [Max Galbusera][@maxgalbu] for the patch +- Squiz SwitchDeclarationSniff now allows exit() as a breaking statement for case/default +- Squiz ValidVariableNameSniff and Zend ValidVariableNameSniff now ignore additional PHP reserved vars + - Thanks to Mikuláš Dítě and Adrian Crepaz for the patch +- Sniff code Squiz.WhiteSpace.MemberVarSpacing.After changed to Squiz.WhiteSpace.MemberVarSpacing.Incorrect (request #20241) + +### Fixed +- Fixed bug #20200 : Invalid JSON produced with specific error message +- Fixed bug #20204 : Ruleset exclude checks are case sensitive +- Fixed bug #20213 : Invalid error, Inline IF must be declared on single line +- Fixed bug #20225 : array_merge() that takes more than one line generates error +- Fixed bug #20230 : Squiz ControlStructureSpacing sniff assumes specific condition formatting +- Fixed bug #20240 : Squiz block comment sniff fails when newline present +- Fixed bug #20247 : The Squiz.WhiteSpace.ControlStructureSpacing sniff and do-while + - Thanks to [Alexander Obuhovich][@aik099] for the patch +- Fixed bug #20248 : The Squiz_Sniffs_WhiteSpace_ControlStructureSpacingSniff sniff and empty scope +- Fixed bug #20252 : Uninitialized string offset when package name starts with underscore + +## [2.0.0a1] - 2014-02-05 +### Changed +- Added the phpcbf script to automatically fix many errors found by the phpcs script +- Added report type --report=diff to show suggested changes to fix coding standard violations +- The --report argument now allows for custom reports to be used + - Use the full path to your custom report class as the report name +- The --extensions argument is now respected when passing filenames; not just with directories +- The --extensions argument now allows you to specify the tokenizer for each extension + - e.g., --extensions=module/php,es/js +- Command line arguments can now be set in ruleset files + - e.g., arg name="report" value="summary" (print summary report; same as --report=summary) + - e.g., arg value="sp" (print source and progress information; same as -sp) + - The -vvv, --sniffs, --standard and -l command line arguments cannot be set in this way +- Sniff process() methods can not optionally return a token to ignore up to + - If returned, the sniff will not be executed again until the passed token is reached in the file + - Useful if you are looking for tokens like T_OPEN_TAG but only want to process the first one +- Removed the comment parser classes and replaced it with a simple comment tokenizer + - T_DOC_COMMENT tokens are now tokenized into T_DOC_COMMENT_* tokens so they can be used more easily + - This change requires a significant rewrite of sniffs that use the comment parser + - This change requires minor changes to sniffs that listen for T_DOC_COMMENT tokens directly +- Added Generic DocCommentSniff to check generic doc block formatting + - Removed doc block formatting checks from PEAR ClassCommentSniff + - Removed doc block formatting checks from PEAR FileCommentSniff + - Removed doc block formatting checks from PEAR FunctionCommentSniff + - Removed doc block formatting checks from Squiz ClassCommentSniff + - Removed doc block formatting checks from Squiz FileCommentSniff + - Removed doc block formatting checks from Squiz FunctionCommentSniff + - Removed doc block formatting checks from Squiz VariableCommentSniff +- Squiz DocCommentAlignmentSniff has had its error codes changed + - NoSpaceBeforeTag becomes NoSpaceAfterStar + - SpaceBeforeTag becomes SpaceAfterStar + - SpaceBeforeAsterisk becomes SpaceBeforeStar +- Generic MultipleStatementAlignment now aligns assignments within a block so they fit within their max padding setting + - The sniff previously requested the padding as 1 space if max padding was exceeded + - It now aligns the assignment with surrounding assignments if it can + - Removed property ignoreMultiline as multi-line assignments are now handled correctly and should not be ignored +- Squiz FunctionClosingBraceSpaceSniff now requires a blank line before the brace in all cases except function args +- Added error Squiz.Commenting.ClassComment.SpacingAfter to ensure there are no blank lines after a class comment +- Added error Squiz.WhiteSpace.MemberVarSpacing.AfterComment to ensure there are no blank lines after a member var comment + - Fixes have also been corrected to not strip the member var comment or indent under some circumstances + - Thanks to [Mark Scherer][@dereuromark] for help with this fix +- Added error Squiz.Commenting.FunctionCommentThrowTag.Missing to ensure a throw is documented +- Removed error Squiz.Commenting.FunctionCommentThrowTag.WrongType +- Content passed via STDIN can now specify the filename to use so that sniffs can run the correct filename checks + - Ensure the first line of the content is: phpcs_input_file: /path/to/file +- Squiz coding standard now enforces no closing PHP tag at the end of a pure PHP file +- Squiz coding standard now enforces a single newline character at the end of the file +- Squiz ClassDeclarationSniff no longer checks for a PHP ending tag after a class definition +- Squiz ControlStructureSpacingSniff now checks TRY and CATCH statements as well +- Removed MySource ChannelExceptionSniff + +## [1.5.2] - 2014-02-05 +### Changed +- Improved support for the PHP 5.5. classname::class syntax + - PSR2 SwitchDeclarationSniff no longer throws errors when this syntax is used in CASE conditions +- Improved support for negative checks of instanceOf in Squiz ComparisonOperatorUsageSniff + - Thanks to [Martin Winkel][@storeman] for the patch +- Generic FunctionCallArgumentSpacingSniff now longer complains about space before comma when using here/nowdocs + - Thanks to [Richard van Velzen][@rvanvelzen] for the patch +- Generic LowerCaseConstantSniff and UpperCaseConstantSniff now ignore class constants + - Thanks to [Kristopher Wilson][@mrkrstphr] for the patch +- PEAR FunctionCallSignatureSniff now has settings to specify how many spaces should appear before/after parentheses + - Override the 'requiredSpacesAfterOpen' and 'requiredSpacesBeforeClose' settings in a ruleset.xml file to change + - Default remains at 0 for both + - Thanks to [Astinus Eberhard][@Astinus-Eberhard] for the patch +- PSR2 ControlStructureSpacingSniff now has settings to specify how many spaces should appear before/after parentheses + - Override the 'requiredSpacesAfterOpen' and 'requiredSpacesBeforeClose' settings in a ruleset.xml file to change + - Default remains at 0 for both + - Thanks to [Astinus Eberhard][@Astinus-Eberhard] for the patch +- Squiz ForEachLoopDeclarationSniff now has settings to specify how many spaces should appear before/after parentheses + - Override the 'requiredSpacesAfterOpen' and 'requiredSpacesBeforeClose' settings in a ruleset.xml file to change + - Default remains at 0 for both + - Thanks to [Astinus Eberhard][@Astinus-Eberhard] for the patch +- Squiz ForLoopDeclarationSniff now has settings to specify how many spaces should appear before/after parentheses + - Override the 'requiredSpacesAfterOpen' and 'requiredSpacesBeforeClose' settings in a ruleset.xml file to change + - Default remains at 0 for both + - Thanks to [Astinus Eberhard][@Astinus-Eberhard] for the patch +- Squiz FunctionDeclarationArgumentSpacingSniff now has settings to specify how many spaces should appear before/after parentheses + - Override the 'requiredSpacesAfterOpen' and 'requiredSpacesBeforeClose' settings in a ruleset.xml file to change + - Default remains at 0 for both + - Thanks to [Astinus Eberhard][@Astinus-Eberhard] for the patch +- Removed UnusedFunctionParameter, CyclomaticComplexity and NestingLevel from the Squiz standard +- Generic FixmeSniff and TodoSniff now work correctly with accented characters + +### Fixed +- Fixed bug #20145 : Custom ruleset preferences directory over installed standard +- Fixed bug #20147 : phpcs-svn-pre-commit - no more default error report +- Fixed bug #20151 : Problem handling "if(): ... else: ... endif;" syntax +- Fixed bug #20190 : Invalid regex in Squiz_Sniffs_WhiteSpace_SuperfluousWhitespaceSniff + +## [1.5.1] - 2013-12-12 +### Changed +- Config values can now be set at runtime using the command line argument [--runtime-set key value] + - Runtime values are the same as config values, but are not written to the main config file + - Thanks to [Wim Godden][@wimg] for the patch +- Config values can now be set in ruleset files + - e.g., config name="zend_ca_path" value="/path/to/ZendCodeAnalyzer" + - Can not be used to set config values that override command line values, such as show_warnings + - Thanks to [Jonathan Marcil][@jmarcil] for helping with the patch +- Added a new installed_paths config value to allow for the setting of directories that contain standards + - By default, standards have to be installed into the CodeSniffer/Standards directory to be considered installed + - New config value allows a list of paths to be set in addition to this internal path + - Installed standards appear when using the -i arg, and can be referenced in rulesets using only their name + - Set paths by running: phpcs --config-set installed_paths /path/one,/path/two,... +- PSR2 ClassDeclarationSniff now allows a list of extended interfaces to be split across multiple lines +- Squiz DoubleQuoteUsageSniff now allows \b in double quoted strings +- Generic ForbiddenFunctionsSniff now ignores object creation + - This is a further fix for bug #20100 : incorrect Function mysql() has been deprecated report + +### Fixed +- Fixed bug #20136 : Squiz_Sniffs_WhiteSpace_ScopeKeywordSpacingSniff and Traits +- Fixed bug #20138 : Protected property underscore and camel caps issue (in trait with Zend) + - Thanks to [Gaetan Rousseau][@Naelyth] for the patch +- Fixed bug #20139 : No report file generated on success + +## [1.5.0] - 2013-11-28 +### Changed +- Doc generation is now working again for installed standards + - Includes a fix for limiting the docs to specific sniffs +- Generic ScopeIndentSniff now allows for ignored tokens to be set via ruleset.xml files + - E.g., to ignore comments, override a property using: + - name="ignoreIndentationTokens" type="array" value="T_COMMENT,T_DOC_COMMENT" +- PSR2 standard now ignores comments when checking indentation rules +- Generic UpperCaseConstantNameSniff no longer reports errors where constants are used (request #20090) + - It still reports errors where constants are defined +- Individual messages can now be excluded in ruleset.xml files using the exclude tag (request #20091) + - Setting message severity to 0 continues to be supported +- Squiz OperatorSpacingSniff no longer throws errors for the ?: short ternary operator + - Thanks to [Antoine Musso][@hashar] for the patch +- Comment parser now supports non-English characters when splitting comment lines into words + - Thanks to [Nik Sun][@CandySunPlus] for the patch +- Exit statements are now recognised as valid closers for CASE and DEFAULT blocks + - Thanks to [Maksim Kochkin][@ksimka] for the patch +- PHP_CodeSniffer_CLI::process() can now be passed an incomplete array of CLI values + - Missing values will be set to the CLI defaults + - Thanks to [Maksim Kochkin][@ksimka] for the patch + +### Fixed +- Fixed bug #20093 : Bug with ternary operator token +- Fixed bug #20097 : CLI.php throws error in php 5.2 +- Fixed bug #20100 : incorrect Function mysql() has been deprecated report +- Fixed bug #20119 : PHP warning: invalid argument to str_repeat() in SVN blame report with -s +- Fixed bug #20123 : PSR2 complains about an empty second statement in for-loop +- Fixed bug #20131 : PHP errors in svnblame report, if there are files not under version control +- Fixed bug #20133 : Allow "HG: hg_id" as value for @version tag + +## [1.4.8] - 2013-11-26 +### Changed +- Generic ScopeIndentSniff now allows for ignored tokens to be set via ruleset.xml files + - E.g., to ignore comments, override a property using: + - name="ignoreIndentationTokens" type="array" value="T_COMMENT,T_DOC_COMMENT" +- PSR2 standard now ignores comments when checking indentation rules +- Squiz OperatorSpacingSniff no longer throws errors for the ?: short ternary operator + - Thanks to [Antoine Musso][@hashar] for the patch +- Comment parser now supports non-English characters when splitting comment lines into words + - Thanks to [Nik Sun][@CandySunPlus] for the patch +- Exit statements are now recognised as valid closers for CASE and DEFAULT blocks + - Thanks to [Maksim Kochkin][@ksimka] for the patch +- PHP_CodeSniffer_CLI::process() can now be passed an incomplete array of CLI values + - Missing values will be set to the CLI defaults + - Thanks to [Maksim Kochkin][@ksimka] for the patch + +### Fixed +- Fixed bug #20097 : CLI.php throws error in php 5.2 +- Fixed bug #20100 : incorrect Function mysql() has been deprecated report +- Fixed bug #20119 : PHP warning: invalid argument to str_repeat() in SVN blame report with -s +- Fixed bug #20123 : PSR2 complains about an empty second statement in for-loop +- Fixed bug #20131 : PHP errors in svnblame report, if there are files not under version control +- Fixed bug #20133 : Allow "HG: hg_id" as value for @version tag + +## [1.5.0RC4] - 2013-09-26 +### Changed +- You can now restrict violations to individual sniff codes using the --sniffs command line argument + - Previously, this only restricted violations to an entire sniff and not individual messages + - If you have scripts calling PHP_CodeSniffer::process() or creating PHP_CodeSniffer_File objects, you must update your code + - The array of restrictions passed to PHP_CodeSniffer::process() must now be an array of sniff codes instead of class names + - The PHP_CodeSniffer_File::__construct() method now requires an array of restrictions to be passed +- Doc generation is now working again +- Progress information now shows the percentage complete at the end of each line +- Added report type --report=junit to show the error list in a JUnit compatible format + - Thanks to [Oleg Lobach][@bladeofsteel] for the contribution +- Added support for the PHP 5.4 callable type hint +- Fixed problem where some file content could be ignored when checking STDIN +- Version information is now printed when installed via composer or run from a Git clone (request #20050) +- Added Squiz DisallowBooleanStatementSniff to ban boolean operators outside of control structure conditions +- The CSS tokenizer is now more reliable when encountering 'list' and 'break' strings +- Coding standard ignore comments can now appear instead doc blocks as well as inline comments + - Thanks to [Stuart Langley][@sjlangley] for the patch +- Generic LineLengthSniff now ignores SVN URL and Head URL comments + - Thanks to [Karl DeBisschop][@kdebisschop] for the patch +- PEAR MultiLineConditionSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- PEAR MultiLineAssignmentSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- PEAR FunctionDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- Squiz SwitchDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- Squiz CSS IndentationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Hugo Fonseca][@fonsecas72] for the patch +- Squiz and MySource File and Function comment sniffs now allow all tags and don't require a particular licence +- Squiz standard now allows lines to be 120 characters long before warning; up from 85 +- Squiz LowercaseStyleDefinitionSniff no longer throws errors for class names in nested style definitions +- Squiz ClassFileNameSniff no longer throws errors when checking STDIN +- Squiz CSS sniffs no longer generate errors for IE filters +- Squiz CSS IndentationSniff no longer sees comments as blank lines +- Squiz LogicalOperatorSpacingSniff now ignores whitespace at the end of a line +- Squiz.Scope.MethodScope.Missing error message now mentions 'visibility' instead of 'scope modifier' + - Thanks to [Renat Akhmedyanov][@r3nat] for the patch +- Added support for the PSR2 multi-line arguments errata +- The PSR2 standard no longer throws errors for additional spacing after a type hint +- PSR UseDeclarationSniff no longer throws errors for USE statements inside TRAITs + +### Fixed +- Fixed cases where code was incorrectly assigned the T_GOTO_LABEL token when used in a complex CASE condition +- Fixed bug #20026 : Check for multi-line arrays that should be single-line is slightly wrong + - Adds new error message for single-line arrays that end with a comma +- Fixed bug #20029 : ForbiddenFunction sniff incorrectly recognizes methods in USE clauses +- Fixed bug #20043 : Mis-interpretation of Foo::class +- Fixed bug #20044 : PSR1 camelCase check does not ignore leading underscores +- Fixed bug #20045 : Errors about indentation for closures with multi-line 'use' in functions +- Fixed bug #20051 : Undefined index: scope_opener / scope_closer + - Thanks to [Anthon Pang][@robocoder] for the patch + +## [1.4.7] - 2013-09-26 +### Changed +- Added report type --report=junit to show the error list in a JUnit compatible format + - Thanks to [Oleg Lobach][@bladeofsteel] for the contribution +- Added support for the PHP 5.4 callable type hint +- Fixed problem where some file content could be ignored when checking STDIN +- Version information is now printed when installed via composer or run from a Git clone (request #20050) +- The CSS tokenizer is now more reliable when encountering 'list' and 'break' strings +- Coding standard ignore comments can now appear instead doc blocks as well as inline comments + - Thanks to [Stuart Langley][@sjlangley] for the patch +- Generic LineLengthSniff now ignores SVN URL and Head URL comments + - Thanks to [Karl DeBisschop][@kdebisschop] for the patch +- PEAR MultiLineConditionSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- PEAR MultiLineAssignmentSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- PEAR FunctionDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- Squiz SwitchDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Szabolcs Sulik][@blerou] for the patch +- Squiz CSS IndentationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the 'indent' setting in a ruleset.xml file to change + - Thanks to [Hugo Fonseca][@fonsecas72] for the patch +- Squiz and MySource File and Function comment sniffs now allow all tags and don't require a particular licence +- Squiz LowercaseStyleDefinitionSniff no longer throws errors for class names in nested style definitions +- Squiz ClassFileNameSniff no longer throws errors when checking STDIN +- Squiz CSS sniffs no longer generate errors for IE filters +- Squiz CSS IndentationSniff no longer sees comments as blank lines +- Squiz LogicalOperatorSpacingSniff now ignores whitespace at the end of a line +- Squiz.Scope.MethodScope.Missing error message now mentions 'visibility' instead of 'scope modifier' + - Thanks to [Renat Akhmedyanov][@r3nat] for the patch +- Added support for the PSR2 multi-line arguments errata +- The PSR2 standard no longer throws errors for additional spacing after a type hint +- PSR UseDeclarationSniff no longer throws errors for USE statements inside TRAITs + +### Fixed +- Fixed bug #20026 : Check for multi-line arrays that should be single-line is slightly wrong + - Adds new error message for single-line arrays that end with a comma +- Fixed bug #20029 : ForbiddenFunction sniff incorrectly recognizes methods in USE clauses +- Fixed bug #20043 : Mis-interpretation of Foo::class +- Fixed bug #20044 : PSR1 camelCase check does not ignore leading underscores +- Fixed bug #20045 : Errors about indentation for closures with multi-line 'use' in functions + +## [1.5.0RC3] - 2013-07-25 +### Changed +- Added report type --report=json to show the error list and total counts for all checked files + - Thanks to [Jeffrey Fisher][@jeffslofish] for the contribution +- PHP_CodeSniffer::isCamelCaps now allows for acronyms at the start of a string if the strict flag is FALSE + - acronyms are defined as at least 2 uppercase characters in a row + - e.g., the following is now valid camel caps with strict set to FALSE: XMLParser +- The PHP tokenizer now tokenizes goto labels as T_GOTO_LABEL instead of T_STRING followed by T_COLON +- The JS tokenizer now has support for the T_THROW token +- Symlinked directories inside CodeSniffer/Standards and in ruleset.xml files are now supported + - Only available since PHP 5.2.11 and 5.3.1 + - Thanks to [Maik Penz][@goatherd] for the patch +- The JS tokenizer now correctly identifies T_INLINE_ELSE tokens instead of leaving them as T_COLON + - Thanks to [Arnout Boks][@aboks] for the patch +- Explaining a standard (phpcs -e) that uses namespaces now works correctly +- Restricting a check to specific sniffs (phpcs --sniffs=...) now works correctly with namespaced sniffs + - Thanks to [Maik Penz][@goatherd] for the patch +- Docs added for the entire Generic standard, and many sniffs from other standards are now documented as well + - Thanks to [Spencer Rinehart][@nubs] for the contribution +- Clearer error message for when the sniff class name does not match the directory structure +- Generated HTML docs now correctly show the open PHP tag in code comparison blocks +- Added Generic InlineHTMLSniff to ensure a file only contains PHP code +- Added Squiz ShorthandSizeSniff to check that CSS sizes are using shorthand notation only when 1 or 2 values are used +- Added Squiz ForbiddenStylesSniff to ban the use of some deprecated browser-specific styles +- Added Squiz NamedColoursSniff to ban the use of colour names +- PSR2 standard no longer enforces no whitespace between the closing parenthesis of a function call and the semicolon +- PSR2 ClassDeclarationSniff now ignores empty classes when checking the end brace position +- PSR2 SwitchDeclarationSniff no longer reports errors for empty lines between CASE statements +- PEAR ObjectOperatorIndentSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the indent setting in a ruleset.xml file to change + - Thanks to [Andrey Mindubaev][@covex-nn] for the patch +- Squiz FileExtensionSniff now supports traits + - Thanks to [Lucas Green][@mythril] for the patch +- Squiz ArrayDeclarationSniff no longer reports errors for no comma at the end of a line that contains a function call +- Squiz SwitchDeclarationSniff now supports T_CONTINUE and T_THROW as valid case/default breaking statements +- Squiz CommentedOutCodeSniff is now better at ignoring commented out HTML, XML and regular expressions +- Squiz DisallowComparisonAssignmentSniff no longer throws errors for the third expression in a FOR statement +- Squiz ColourDefinitionSniff no longer throws errors for some CSS class names +- Squiz ControlStructureSpacingSniff now supports all types of CASE/DEFAULT breaking statements +- Generic CallTimePassByReferenceSniff now reports errors for functions called using a variable + - Thanks to [Maik Penz][@goatherd] for the patch +- Generic ConstructorNameSniff no longer throws a notice for abstract constructors inside abstract classes + - Thanks to [Spencer Rinehart][@nubs] for the patch +- Squiz ComparisonOperatorUsageSniff now checks inside elseif statements + - Thanks to [Arnout Boks][@aboks] for the patch +- Squiz OperatorSpacingSniff now reports errors for no spacing around inline then and else tokens + - Thanks to [Arnout Boks][@aboks] for the patch + +### Fixed +- Fixed bug #19811 : Comments not ignored in all cases in AbstractPatternSniff + - Thanks to [Erik Wiffin][@erikwiffin] for the patch +- Fixed bug #19892 : ELSE with no braces causes incorrect SWITCH break statement indentation error +- Fixed bug #19897 : Indenting warnings in templates not consistent +- Fixed bug #19908 : PEAR MultiLineCondition Does Not Apply elseif +- Fixed bug #19930 : option --report-file generate an empty file +- Fixed bug #19935 : notify-send reports do not vanish in gnome-shell + - Thanks to [Christian Weiske][@cweiske] for the patch +- Fixed bug #19944 : docblock squiz sniff "return void" trips over return in lambda function +- Fixed bug #19953 : PSR2 - Spaces before interface name for abstract class +- Fixed bug #19956 : phpcs warns for Type Hint missing Resource +- Fixed bug #19957 : Does not understand trait method aliasing +- Fixed bug #19968 : Permission denied on excluded directory +- Fixed bug #19969 : Sniffs with namespace not recognized in reports +- Fixed bug #19997 : Class names incorrectly detected as constants + +## [1.4.6] - 2013-07-25 +### Changed +- Added report type --report=json to show the error list and total counts for all checked files + - Thanks to [Jeffrey Fisher][@jeffslofish] for the contribution +- The JS tokenizer now has support for the T_THROW token +- Symlinked directories inside CodeSniffer/Standards and in ruleset.xml files are now supported + - Only available since PHP 5.2.11 and 5.3.1 + - Thanks to [Maik Penz][@goatherd] for the patch +- The JS tokenizer now correctly identifies T_INLINE_ELSE tokens instead of leaving them as T_COLON + - Thanks to [Arnout Boks][@aboks] for the patch +- Explaining a standard (phpcs -e) that uses namespaces now works correctly +- Restricting a check to specific sniffs (phpcs --sniffs=...) now works correctly with namespaced sniffs + - Thanks to [Maik Penz][@goatherd] for the patch +- Docs added for the entire Generic standard, and many sniffs from other standards are now documented as well + - Thanks to [Spencer Rinehart][@nubs] for the contribution +- Clearer error message for when the sniff class name does not match the directory structure +- Generated HTML docs now correctly show the open PHP tag in code comparison blocks +- Added Generic InlineHTMLSniff to ensure a file only contains PHP code +- Added Squiz ShorthandSizeSniff to check that CSS sizes are using shorthand notation only when 1 or 2 values are used +- Added Squiz ForbiddenStylesSniff to ban the use of some deprecated browser-specific styles +- Added Squiz NamedColoursSniff to ban the use of colour names +- PSR2 standard no longer enforces no whitespace between the closing parenthesis of a function call and the semicolon +- PSR2 ClassDeclarationSniff now ignores empty classes when checking the end brace position +- PSR2 SwitchDeclarationSniff no longer reports errors for empty lines between CASE statements +- PEAR ObjectOperatorIndentSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the indent setting in a ruleset.xml file to change + - Thanks to [Andrey Mindubaev][@covex-nn] for the patch +- Squiz FileExtensionSniff now supports traits + - Thanks to [Lucas Green][@mythril] for the patch +- Squiz ArrayDeclarationSniff no longer reports errors for no comma at the end of a line that contains a function call +- Squiz SwitchDeclarationSniff now supports T_CONTINUE and T_THROW as valid case/default breaking statements +- Squiz CommentedOutCodeSniff is now better at ignoring commented out HTML, XML and regular expressions +- Squiz DisallowComparisonAssignmentSniff no longer throws errors for the third expression in a FOR statement +- Squiz ColourDefinitionSniff no longer throws errors for some CSS class names +- Squiz ControlStructureSpacingSniff now supports all types of CASE/DEFAULT breaking statements +- Generic CallTimePassByReferenceSniff now reports errors for functions called using a variable + - Thanks to [Maik Penz][@goatherd] for the patch +- Generic ConstructorNameSniff no longer throws a notice for abstract constructors inside abstract classes + - Thanks to [Spencer Rinehart][@nubs] for the patch +- Squiz ComparisonOperatorUsageSniff now checks inside elseif statements + - Thanks to [Arnout Boks][@aboks] for the patch +- Squiz OperatorSpacingSniff now reports errors for no spacing around inline then and else tokens + - Thanks to [Arnout Boks][@aboks] for the patch + +### Fixed +- Fixed bug #19811 : Comments not ignored in all cases in AbstractPatternSniff + - Thanks to [Erik Wiffin][@erikwiffin] for the patch +- Fixed bug #19892 : ELSE with no braces causes incorrect SWITCH break statement indentation error +- Fixed bug #19897 : Indenting warnings in templates not consistent +- Fixed bug #19908 : PEAR MultiLineCondition Does Not Apply elseif +- Fixed bug #19913 : Running phpcs in interactive mode causes warnings + - Thanks to [Harald Franndorfer][pear-gemineye] for the patch +- Fixed bug #19935 : notify-send reports do not vanish in gnome-shell + - Thanks to [Christian Weiske][@cweiske] for the patch +- Fixed bug #19944 : docblock squiz sniff "return void" trips over return in lambda function +- Fixed bug #19953 : PSR2 - Spaces before interface name for abstract class +- Fixed bug #19956 : phpcs warns for Type Hint missing Resource +- Fixed bug #19957 : Does not understand trait method aliasing +- Fixed bug #19968 : Permission denied on excluded directory +- Fixed bug #19969 : Sniffs with namespace not recognized in reports +- Fixed bug #19997 : Class names incorrectly detected as constants + +## [1.5.0RC2] - 2013-04-04 +### Changed +- Ruleset processing has been rewritten to be more predictable + - Provides much better support for relative paths inside ruleset files + - May mean that sniffs that were previously ignored are now being included when importing external rulesets + - Ruleset processing output can be seen by using the -vv command line argument + - Internal sniff registering functions have all changed, so please review custom scripts +- You can now pass multiple coding standards on the command line, comma separated (request #19144) + - Works with built-in or custom standards and rulesets, or a mix of both +- You can now exclude directories or whole standards in a ruleset XML file (request #19731) + - e.g., exclude "Generic.Commenting" or just "Generic" + - You can also pass in a path to a directory instead, if you know it +- Added Generic LowerCaseKeywordSniff to ensure all PHP keywords are defined in lowercase + - The PSR2 and Squiz standards now use this sniff +- Added Generic SAPIUsageSniff to ensure the PHP_SAPI constant is used instead of php_sapi_name() (request #19863) +- Squiz FunctionSpacingSniff now has a setting to specify how many lines there should between functions (request #19843) + - Default remains at 2 + - Override the "spacing" setting in a ruleset.xml file to change +- Squiz LowercasePHPFunctionSniff no longer throws errors for the limited set of PHP keywords it was checking + - Add a rule for Generic.PHP.LowerCaseKeyword to your ruleset to replicate this functionality +- Added support for the PHP 5.4 T_CALLABLE token so it can be used in lower PHP versions +- Generic EndFileNoNewlineSniff now supports checking of CSS and JS files +- PSR2 SwitchDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the indent setting in a ruleset.xml file to change + - Thanks to [Asher Snyder][@asnyder] for the patch +- Generic ScopeIndentSniff now has a setting to specify a list of tokens that should be ignored + - The first token on the line is checked and the whole line is ignored if the token is in the array + - Thanks to [Eloy Lafuente][@stronk7] for the patch +- Squiz LowercaseClassKeywordsSniff now checks for the TRAIT keyword + - Thanks to [Anthon Pang][@robocoder] for the patch +- If you create your own PHP_CodeSniffer object, PHPCS will no longer exit when an unknown argument is found + - This allows you to create wrapper scripts for PHPCS more easily +- PSR2 MethodDeclarationSniff no longer generates a notice for methods named "_" + - Thanks to [Bart S][@zBart] for the patch +- Squiz BlockCommentSniff no longer reports that a blank line between a scope closer and block comment is invalid +- Generic DuplicateClassNameSniff no longer reports an invalid error if multiple PHP open tags exist in a file +- Generic DuplicateClassNameSniff no longer reports duplicate errors if multiple PHP open tags exist in a file + +### Fixed +- Fixed bug #19819 : Freeze with syntax error in use statement +- Fixed bug #19820 : Wrong message level in Generic_Sniffs_CodeAnalysis_EmptyStatementSniff +- Fixed bug #19859 : CodeSniffer::setIgnorePatterns API changed +- Fixed bug #19871 : findExtendedClassName doesn't return FQCN on namespaced classes +- Fixed bug #19879 : bitwise and operator interpreted as reference by value + +## [1.4.5] - 2013-04-04 +### Changed +- Added Generic LowerCaseKeywordSniff to ensure all PHP keywords are defined in lowercase + - The PSR2 and Squiz standards now use this sniff +- Added Generic SAPIUsageSniff to ensure the PHP_SAPI constant is used instead of php_sapi_name() (request #19863) +- Squiz FunctionSpacingSniff now has a setting to specify how many lines there should between functions (request #19843) + - Default remains at 2 + - Override the "spacing" setting in a ruleset.xml file to change +- Squiz LowercasePHPFunctionSniff no longer throws errors for the limited set of PHP keywords it was checking + - Add a rule for Generic.PHP.LowerCaseKeyword to your ruleset to replicate this functionality +- Added support for the PHP 5.4 T_CALLABLE token so it can be used in lower PHP versions +- Generic EndFileNoNewlineSniff now supports checking of CSS and JS files +- PSR2 SwitchDeclarationSniff now has a setting to specify how many spaces code should be indented + - Default remains at 4; override the indent setting in a ruleset.xml file to change + - Thanks to [Asher Snyder][@asnyder] for the patch +- Generic ScopeIndentSniff now has a setting to specify a list of tokens that should be ignored + - The first token on the line is checked and the whole line is ignored if the token is in the array + - Thanks to [Eloy Lafuente][@stronk7] for the patch +- Squiz LowercaseClassKeywordsSniff now checks for the TRAIT keyword + - Thanks to [Anthon Pang][@robocoder] for the patch +- If you create your own PHP_CodeSniffer object, PHPCS will no longer exit when an unknown argument is found + - This allows you to create wrapper scripts for PHPCS more easily +- PSR2 MethodDeclarationSniff no longer generates a notice for methods named "_" + - Thanks to [Bart S][@zBart] for the patch +- Squiz BlockCommentSniff no longer reports that a blank line between a scope closer and block comment is invalid +- Generic DuplicateClassNameSniff no longer reports an invalid error if multiple PHP open tags exist in a file +- Generic DuplicateClassNameSniff no longer reports duplicate errors if multiple PHP open tags exist in a file + +### Fixed +- Fixed bug #19819 : Freeze with syntax error in use statement +- Fixed bug #19820 : Wrong message level in Generic_Sniffs_CodeAnalysis_EmptyStatementSniff +- Fixed bug #19859 : CodeSniffer::setIgnorePatterns API changed +- Fixed bug #19871 : findExtendedClassName doesn't return FQCN on namespaced classes +- Fixed bug #19879 : bitwise and operator interpreted as reference by value + +## [1.5.0RC1] - 2013-02-08 +### Changed +- Reports have been completely rewritten to consume far less memory + - Each report is incrementally written to the file system during a run and then printed out when the run ends + - There is no longer a need to keep the list of errors and warnings in memory during a run +- Multi-file sniff support has been removed because they are too memory intensive + - If you have a custom multi-file sniff, you can convert it into a standard sniff quite easily + - See CodeSniffer/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php for an example + +## [1.4.4] - 2013-02-07 +### Changed +- Ignored lines no longer cause the summary report to show incorrect error and warning counts + - Thanks to [Bert Van Hauwaert][@becoded] for the patch +- Added Generic CSSLintSniff to run CSSLint over a CSS file and report warnings + - Set full command to run CSSLint using phpcs --config-set csslint_path /path/to/csslint + - Thanks to [Roman Levishchenko][@index0h] for the contribution +- Added PSR2 ControlStructureSpacingSniff to ensure there are no spaces before and after parenthesis in control structures + - Fixes bug #19732 : PSR2: some control structures errors not reported +- Squiz commenting sniffs now support non-English characters when checking for capital letters + - Thanks to [Roman Levishchenko][@index0h] for the patch +- Generic EndFileNewlineSniff now supports JS and CSS files + - Thanks to [Denis Ryabkov][@dryabkov] for the patch +- PSR1 SideEffectsSniff no longer reports constant declarations as side effects +- Notifysend report now supports notify-send versions before 0.7.3 + - Thanks to [Ken Guest][@kenguest] for the patch +- PEAR and Squiz FunctionCommentSniffs no longer report errors for misaligned argument comments when they are blank + - Thanks to [Thomas Peterson][@boonkerz] for the patch +- Squiz FunctionDeclarationArgumentSpacingSniff now works correctly for equalsSpacing values greater than 0 + - Thanks to [Klaus Purer][@klausi] for the patch +- Squiz SuperfluousWhitespaceSniff no longer throws errors for CSS files with no newline at the end +- Squiz SuperfluousWhitespaceSniff now allows a single newline at the end of JS and CSS files + +### Fixed +- Fixed bug #19755 : Token of T_CLASS type has no scope_opener and scope_closer keys +- Fixed bug #19759 : Squiz.PHP.NonExecutableCode fails for return function()... +- Fixed bug #19763 : Use statements for traits not recognised correctly for PSR2 code style +- Fixed bug #19764 : Instead of for traits throws uppercase constant name errors +- Fixed bug #19772 : PSR2_Sniffs_Namespaces_UseDeclarationSniff does not properly recognize last use +- Fixed bug #19775 : False positive in NonExecutableCode sniff when not using curly braces +- Fixed bug #19782 : Invalid found size functions in loop when using object operator +- Fixed bug #19799 : config folder is not created automatically +- Fixed bug #19804 : JS Tokenizer wrong /**/ parsing + +## [1.4.3] - 2012-12-04 +### Changed +- Added support for the PHP 5.5 T_FINALLY token to detect try/catch/finally statements +- Added empty CodeSniffer.conf to enable config settings for Composer installs +- Added Generic EndFileNoNewlineSniff to ensure there is no newline at the end of a file +- Autoloader can now load PSR-0 compliant classes + - Thanks to [Maik Penz][@goatherd] for the patch +- Squiz NonExecutableCodeSniff no longer throws error for multi-line RETURNs inside CASE statements + - Thanks to [Marc Ypes][@ceeram] for the patch +- Squiz OperatorSpacingSniff no longer reports errors for negative numbers inside inline THEN statements + - Thanks to [Klaus Purer][@klausi] for the patch +- Squiz OperatorSpacingSniff no longer reports errors for the assignment of operations involving negative numbers +- Squiz SelfMemberReferenceSniff can no longer get into an infinite loop when checking a static call with a namespace + - Thanks to [Andy Grunwald][@andygrunwald] for the patch + +### Fixed +- Fixed bug #19699 : Generic.Files.LineLength giving false positives when tab-width is used +- Fixed bug #19726 : Wrong number of spaces expected after instanceof static +- Fixed bug #19727 : PSR2: no error reported when using } elseif { + +## [1.4.2] - 2012-11-09 +### Changed +- PHP_CodeSniffer can now be installed using Composer + - Require squizlabs/php_codesniffer in your composer.json file + - Thanks to [Rob Bast][@alcohol], [Stephen Rees-Carter][@valorin], [Stefano Kowalke][@Konafets] and [Ivan Habunek][@ihabunek] for help with this +- Squiz BlockCommentSniff and InlineCommentSniff no longer report errors for trait block comments +- Squiz SelfMemberReferenceSniff now supports namespaces + - Thanks to [Andy Grunwald][@andygrunwald] for the patch +- Squiz FileCommentSniff now uses tag names inside the error codes for many messages + - This allows you to exclude specific missing, out of order etc., tags +- Squiz SuperfluousWhitespaceSniff now has an option to ignore blank lines + - This will stop errors being reported for lines that contain only whitespace + - Set the ignoreBlankLines property to TRUE in your ruleset.xml file to enable this +- PSR2 no longer reports errors for whitespace at the end of blank lines + +### Fixed +- Fixed gitblame report not working on Windows + - Thanks to [Rogerio Prado de Jesus][@rogeriopradoj] +- Fixed an incorrect error in Squiz OperatorSpacingSniff for default values inside a closure definition +- Fixed bug #19691 : SubversionPropertiesSniff fails to find missing properties + - Thanks to [Kevin Winahradsky][pear-kwinahradsky] for the patch +- Fixed bug #19692 : DisallowMultipleAssignments is triggered by a closure +- Fixed bug #19693 : exclude-patterns no longer work on specific messages +- Fixed bug #19694 : Squiz.PHP.LowercasePHPFunctions incorrectly matches return by ref functions + +## [1.4.1] - 2012-11-02 +### Changed +- All ignore patterns have been reverted to being checked against the absolute path of a file + - Patterns can be specified to be relative in a ruleset.xml file, but nowhere else + - e.g., [exclude-pattern type="relative"]^tests/*[/exclude-pattern] (with angle brackets, not square brackets) +- Added support for PHP tokenizing of T_INLINE_ELSE colons, so this token type is now available + - Custom sniffs that rely on looking for T_COLON tokens inside inline if statements must be changed to use the new token + - Fixes bug #19666 : PSR1.Files.SideEffects throws a notice Undefined index: scope_closer +- Messages can now be changed from errors to warnings (and vice versa) inside ruleset.xml files + - As you would with "message" and "severity", specify a "type" tag under a "rule" tag and set the value to "error" or "warning" +- PHP_CodeSniffer will now generate a warning on files that it detects have mixed line endings + - This warning has the code Internal.LineEndings.Mixed and can be overridden in a ruleset.xml file + - Thanks to [Vit Brunner][@tasuki] for help with this +- Sniffs inside PHP 5.3 namespaces are now supported, along with the existing underscore-style emulated namespaces + - For example: namespace MyStandard\Sniffs\Arrays; class ArrayDeclarationSniff implements \PHP_CodeSniffer_Sniff { ... + - Thanks to [Till Klampaeckel][@till] for the patch +- Generic DuplicateClassNameSniff is no longer a multi-file sniff, so it won't max out your memory + - Multi-file sniff support should be considered deprecated as standard sniffs can now do the same thing +- Added Generic DisallowSpaceIndent to check that files are indented using tabs +- Added Generic OneClassPerFileSniff to check that only one class is defined in each file + - Thanks to [Andy Grunwald][@andygrunwald] for the contribution +- Added Generic OneInterfacePerFileSniff to check that only one interface is defined in each file + - Thanks to [Andy Grunwald][@andygrunwald] for the contribution +- Added Generic LowercasedFilenameSniff to check that filenames are lowercase + - Thanks to [Andy Grunwald][@andygrunwald] for the contribution +- Added Generic ClosingPHPTagSniff to check that each open PHP tag has a corresponding close tag + - Thanks to [Andy Grunwald][@andygrunwald] for the contribution +- Added Generic CharacterBeforePHPOpeningTagSniff to check that the open PHP tag is the first content in a file + - Thanks to [Andy Grunwald][@andygrunwald] for the contribution +- Fixed incorrect errors in Squiz OperatorBracketSniff and OperatorSpacingSniff for negative numbers in CASE statements + - Thanks to [Arnout Boks][@aboks] for the patch +- Generic CamelCapsFunctionNameSniff no longer enforces exact case matching for PHP magic methods +- Generic CamelCapsFunctionNameSniff no longer throws errors for overridden SOAPClient methods prefixed with double underscores + - Thanks to [Dorian Villet][@gnutix] for the patch +- PEAR ValidFunctionNameSniff now supports traits +- PSR1 ClassDeclarationSniff no longer throws an error for non-namespaced code if PHP version is less than 5.3.0 + +### Fixed +- Fixed bug #19616 : Nested switches cause false error in PSR2 +- Fixed bug #19629 : PSR2 error for inline comments on multi-line argument lists +- Fixed bug #19644 : Alternative syntax, e.g. if/endif triggers Inline Control Structure error +- Fixed bug #19655 : Closures reporting as multi-line when they are not +- Fixed bug #19675 : Improper indent of nested anonymous function bodies in a call +- Fixed bug #19685 : PSR2 catch-22 with empty third statement in for loop +- Fixed bug #19687 : Anonymous functions inside arrays marked as indented incorrectly in PSR2 + +## [1.4.0] - 2012-09-26 +### Changed +- Added PSR1 and PSR2 coding standards that can be used to check your code against these guidelines +- PHP 5.4 short array syntax is now detected and tokens are assigned to the open and close characters + - New tokens are T_OPEN_SHORT_ARRAY and T_CLOSE_SHORT_ARRAY as PHP does not define its own +- Added the ability to explain a coding standard by listing the sniffs that it includes + - The sniff list includes all imported and native sniffs + - Explain a standard by using the -e and --standard=[standard] command line arguments + - E.g., phpcs -e --standard=Squiz + - Thanks to [Ben Selby][@benmatselby] for the idea +- Added report to show results using notify-send + - Use --report=notifysend to generate the report + - Thanks to [Christian Weiske][@cweiske] for the contribution +- The JS tokenizer now recognises RETURN as a valid closer for CASE and DEFAULT inside switch statements +- AbstractPatternSniff now sets the ignoreComments option using a public var rather than through the constructor + - This allows the setting to be overwritten in ruleset.xml files + - Old method remains for backwards compatibility +- Generic LowerCaseConstantSniff and UpperCaseConstantSniff no longer report errors on classes named True, False or Null +- PEAR ValidFunctionNameSniff no longer enforces exact case matching for PHP magic methods +- Squiz SwitchDeclarationSniff now allows RETURN statements to close a CASE or DEFAULT statement +- Squiz BlockCommentSniff now correctly reports an error for blank lines before blocks at the start of a control structure + +### Fixed +- Fixed a PHP notice generated when loading custom array settings from a ruleset.xml file +- Fixed bug #17908 : CodeSniffer does not recognise optional @params + - Thanks to [Pete Walker][pear-pete] for the patch +- Fixed bug #19538 : Function indentation code sniffer checks inside short arrays +- Fixed bug #19565 : Non-Executable Code Sniff Broken for Case Statements with both return and break +- Fixed bug #19612 : Invalid @package suggestion + +## [1.3.6] - 2012-08-08 +### Changed +- Memory usage has been dramatically reduced when using the summary report + - Reduced memory is only available when displaying a single summary report to the screen + - PHP_CodeSniffer will not generate any messages in this case, storing only error counts instead + - Impact is most notable with very high error and warning counts +- Significantly improved the performance of Squiz NonExecutableCodeSniff +- Ignore patterns now check the relative path of a file based on the dir being checked + - Allows ignore patterns to become more generic as the path to the code is no longer included when checking + - Thanks to [Kristof Coomans][@kristofser] for the patch +- Sniff settings can now be changed by specifying a special comment format inside a file + - e.g., // @codingStandardsChangeSetting PEAR.Functions.FunctionCallSignature allowMultipleArguments false + - If you change a setting, don't forget to change it back +- Added Generic EndFileNewlineSniff to ensure PHP files end with a newline character +- PEAR FunctionCallSignatureSniff now includes a setting to force one argument per line in multi-line calls + - Set allowMultipleArguments to false +- Squiz standard now enforces one argument per line in multi-line function calls +- Squiz FunctionDeclarationArgumentSpacingSniff now supports closures +- Squiz OperatorSpacingSniff no longer throws an error for negative values inside an inline THEN statement + - Thanks to [Klaus Purer][@klausi] for the patch +- Squiz FunctionCommentSniff now throws an error for not closing a comment with */ + - Thanks to [Klaus Purer][@klausi] for the patch +- Summary report no longer shows two lines of PHP_Timer output when showing sources + +### Fixed +- Fixed undefined variable error in PEAR FunctionCallSignatureSniff for lines with no indent +- Fixed bug #19502 : Generic.Files.LineEndingsSniff fails if no new-lines in file +- Fixed bug #19508 : switch+return: Closing brace indented incorrectly +- Fixed bug #19532 : The PSR-2 standard don't recognize Null in class names +- Fixed bug #19546 : Error thrown for __call() method in traits + +## [1.3.5] - 2012-07-12 +### Changed +- Added Generic CamelCapsFunctionNameSniff to just check if function and method names use camel caps + - Does not allow underscore prefixes for private/protected methods + - Defaults to strict checking, where two uppercase characters can not be next to each other + - Strict checking can be disabled in a ruleset.xml file +- Squiz FunctionDeclarationArgumentSpacing now has a setting to specify how many spaces should surround equals signs + - Default remains at 0 + - Override the equalsSpacing setting in a ruleset.xml file to change +- Squiz ClassDeclarationSniff now throws errors for > 1 space before extends/implements class name with ns separator +- Squiz standard now warns about deprecated functions using Generic DeprecatedFunctionsSniff +- PEAR FunctionDeclarationSniff now reports an error for multiple spaces after the FUNCTION keyword and around USE +- PEAR FunctionDeclarationSniff now supports closures +- Squiz MultiLineFunctionDeclarationSniff now supports closures +- Exclude rules written for Unix systems will now work correctly on Windows + - Thanks to [Walter Tamboer][@waltertamboer] for the patch +- The PHP tokenizer now recognises T_RETURN as a valid closer for T_CASE and T_DEFAULT inside switch statements + +### Fixed +- Fixed duplicate message codes in Generic OpeningFunctionBraceKernighanRitchieSniff +- Fixed bug #18651 : PHPunit Test cases for custom standards are not working on Windows +- Fixed bug #19416 : Shorthand arrays cause bracket spacing errors +- Fixed bug #19421 : phpcs doesn't recognize ${x} as equivalent to $x +- Fixed bug #19428 : PHPCS Report "hgblame" doesn't support windows paths + - Thanks to [Justin Rovang][@rovangju] for the patch +- Fixed bug #19448 : Problem with detecting remote standards +- Fixed bug #19463 : Anonymous functions incorrectly being flagged by NonExecutableCodeSniff +- Fixed bug #19469 : PHP_CodeSniffer_File::getMemberProperties() sets wrong scope +- Fixed bug #19471 : phpcs on Windows, when using Zend standard, doesn't catch problems + - Thanks to [Ivan Habunek][@ihabunek] for the patch +- Fixed bug #19478 : Incorrect indent detection in PEAR standard + - Thanks to [Shane Auckland][@shanethehat] for the patch +- Fixed bug #19483 : Blame Reports fail with space in directory name + +## [1.3.4] - 2012-05-17 +### Changed +- Added missing package.xml entries for new Generic FixmeSniff + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Expected indents for PEAR ScopeClosingBraceSniff and FunctionCallSignatureSniff can now be set in ruleset files + - Both sniffs use a variable called "indent" + - Thanks to [Thomas Despoix][pear-tomdesp] for the patch +- Standards designed to be installed in the PHPCS Standards dir will now work outside this dir as well + - In particular, allows the Drupal CS to work without needing to symlink it into the PHPCS install + - Thanks to [Peter Philipp][@das-peter] for the patch +- Rule references for standards, directories and specific sniffs can now be relative in ruleset.xml files + - For example: ref="../MyStandard/Sniffs/Commenting/DisallowHashCommentsSniff.php" +- Symlinked standards now work correctly, allowing aliasing of installed standards (request #19417) + - Thanks to [Tom Klingenberg][@ktomk] for the patch +- Squiz ObjectInstantiationSniff now allows objects to be returned without assigning them to a variable +- Added Squiz.Commenting.FileComment.MissingShort error message for file comments that only contains tags + - Also stops undefined index errors being generated for these comments +- Debug option -vv now shows tokenizer status for CSS files +- Added support for new gjslint error formats + - Thanks to [Meck][@yesmeck] for the patch +- Generic ScopeIndentSniff now allows comment indents to not be exact even if the exact flag is set + - The start of the comment is still checked for exact indentation as normal +- Fixed an issue in AbstractPatternSniff where comments were not being ignored in some cases +- Fixed an issue in Zend ClosingTagSniff where the closing tag was not always being detected correctly + - Thanks to [Jonathan Robson][@jnrbsn] for the patch +- Fixed an issue in Generic FunctionCallArgumentSpacingSniff where closures could cause incorrect errors +- Fixed an issue in Generic UpperCaseConstantNameSniff where errors were incorrectly reported on goto statements + - Thanks to [Tom Klingenberg][@ktomk] for the patch +- PEAR FileCommentSniff and ClassCommentSniff now support author emails with a single character in the local part + - E.g., a@me.com + - Thanks to Denis Shapkin for the patch + +### Fixed +- Fixed bug #19290 : Generic indent sniffer fails for anonymous functions +- Fixed bug #19324 : Setting show_warnings configuration option does not work +- Fixed bug #19354 : Not recognizing references passed to method +- Fixed bug #19361 : CSS tokenizer generates errors when PHP embedded in CSS file +- Fixed bug #19374 : HEREDOC/NOWDOC Indentation problems +- Fixed bug #19381 : traits and indentations in traits are not handled properly +- Fixed bug #19394 : Notice in NonExecutableCodeSniff +- Fixed bug #19402 : Syntax error when executing phpcs on Windows with parens in PHP path + - Thanks to [Tom Klingenberg][@ktomk] for the patch +- Fixed bug #19411 : magic method error on __construct() + - The fix required a rewrite of AbstractScopeSniff, so please test any sniffs that extend this class +- Fixed bug #19412 : Incorrect error about assigning objects to variables when inside inline IF +- Fixed bug #19413 : php_cs thinks I haven't used a parameter when I have +- Fixed bug #19414 : php_cs seems to not track variables correctly in heredocs + +## [1.3.3] - 2012-02-07 +### Changed +- Added new Generic FixmeSniff that shows error messages for all FIXME comments left in your code + - Thanks to [Sam Graham][@illusori] for the contribution +- The maxPercentage setting in the Squiz CommentedOutCodeSniff can now be overridden in a ruleset.xml file + - Thanks to [Volker Dusch][@edorian] for the patch +- The Checkstyle and XML reports now use XMLWriter + - Only change in output is that empty file tags are no longer produced for files with no violations + - Thanks to [Sebastian Bergmann][@sebastianbergmann] for the patch +- Added PHP_CodeSniffer_Tokens::$bracketTokens to give sniff writers fast access to open and close bracket tokens +- Fixed an issue in AbstractPatternSniff where EOL tokens were not being correctly checked in some cases +- PHP_CodeSniffer_File::getTokensAsString() now detects incorrect length value (request #19313) + +### Fixed +- Fixed bug #19114 : CodeSniffer checks extension even for single file +- Fixed bug #19171 : Show sniff codes option is ignored by some report types + - Thanks to [Dominic Scheirlinck][@dominics] for the patch +- Fixed bug #19188 : Lots of PHP Notices when analyzing the Symfony framework + - First issue was list-style.. lines in CSS files not properly adjusting open/close bracket positions + - Second issue was notices caused by bug #19137 +- Fixed bug #19208 : UpperCaseConstantName reports class members + - Was also a problem with LowerCaseConstantName as well +- Fixed bug #19256 : T_DOC_COMMENT in CSS files breaks ClassDefinitionNameSpacingSniff + - Thanks to [Klaus Purer][@klausi] for the patch +- Fixed bug #19264 : Squiz.PHP.NonExecutableCode does not handle RETURN in CASE without BREAK +- Fixed bug #19270 : DuplicateClassName does not handle namespaces correctly +- Fixed bug #19283 : CSS @media rules cause false positives + - Thanks to [Klaus Purer][@klausi] for the patch + +## [1.3.2] - 2011-12-01 +### Changed +- Added Generic JSHintSniff to run jshint.js over a JS file and report warnings + - Set jshint path using phpcs --config-set jshint_path /path/to/jshint-rhino.js + - Set rhino path using phpcs --config-set rhino_path /path/to/rhino + - Thanks to Alexander Weiß for the contribution +- Nowdocs are now tokenized using PHP_CodeSniffer specific T_NOWDOC tokens for easier identification +- Generic UpperCaseConstantNameSniff no longer throws errors for namespaces + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Squiz NonExecutableCodeSniff now detects code after thrown exceptions + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Squiz OperatorSpacingSniff now ignores references + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Squiz FunctionCommentSniff now reports a missing function comment if it finds a standard code comment instead +- Squiz FunctionCommentThrownTagSniff no longer reports errors if it can't find a function comment + +### Fixed +- Fixed unit tests not running under Windows + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #18964 : "$stackPtr must be of type T_VARIABLE" on heredocs and nowdocs +- Fixed bug #18973 : phpcs is looking for variables in a nowdoc +- Fixed bug #18974 : Blank line causes "Multi-line function call not indented correctly" + - Adds new error message to ban empty lines in multi-line function calls +- Fixed bug #18975 : "Closing parenthesis must be on a line by itself" also causes indentation error + +## 1.3.1 - 2011-11-03 +### Changed +- All report file command line arguments now work with relative paths (request #17240) +- The extensions command line argument now supports multi-part file extensions (request #17227) +- Added report type --report=hgblame to show number of errors/warnings committed by authors in a Mercurial repository + - Has the same functionality as the svnblame report + - Thanks to [Ben Selby][@benmatselby] for the patch +- Added T_BACKTICK token type to make detection of backticks easier (request #18799) +- Added pattern matching support to Generic ForbiddenFunctionsSniff + - If you are extending it and overriding register() or addError() you will need to review your sniff +- Namespaces are now recognised as scope openers, although they do not require braces (request #18043) +- Added new ByteOrderMarkSniff to Generic standard (request #18194) + - Throws an error if a byte order mark is found in any PHP file + - Thanks to [Piotr Karas][pear-ryba] for the contribution +- PHP_Timer output is no longer included in reports when being written to a file (request #18252) + - Also now shown for all report types if nothing is being printed to the screen +- Generic DeprecatedFunctionSniff now reports functions as deprecated and not simply forbidden (request #18288) +- PHPCS now accepts file contents from STDIN (request #18447) + - Example usage: cat temp.php | phpcs [options] -OR- phpcs [options] < temp.php + - Not every sniff will work correctly due to the lack of a valid file path +- PHP_CodeSniffer_Exception no longer extends PEAR_Exception (request #18483) + - PEAR_Exception added a requirement that PEAR had to be installed + - PHP_CodeSniffer is not used as a library, so unlikely to have any impact +- PEAR FileCommentSniff now allows GIT IDs in the version tag (request #14874) +- AbstractVariableSniff now supports heredocs + - Also includes some variable detection fixes + - Thanks to [Sam Graham][@illusori] for the patch +- Squiz FileCommentSniff now enforces rule that package names cannot start with the word Squiz +- MySource AssignThisSniff now allows "this" to be assigned to the private var _self +- PEAR ClassDeclaration sniff now supports indentation checks when using the alternate namespace syntax + - PEAR.Classes.ClassDeclaration.SpaceBeforeBrace message now contains 2 variables instead of 1 + - Sniff allows overriding of the default indent level, which is set to 4 + - Fixes bug #18933 : Alternative namespace declaration syntax confuses scope sniffs + +### Fixed +- Fixed issue in Squiz FileCommentSniff where suggested package name was the same as the incorrect package name +- Fixed some issues with Squiz ArrayDeclarationSniff when using function calls in array values +- Fixed doc generation so it actually works again + - Also now works when being run from an SVN checkout as well as when installed as a PEAR package + - Should fix bug #18949 : Call to private method from static +- Fixed bug #18465 : "self::" does not work in lambda functions + - Also corrects conversion of T_FUNCTION tokens to T_CLOSURE, which was not fixing token condition arrays +- Fixed bug #18543 : CSS Tokenizer deletes too many # +- Fixed bug #18624 : @throws namespace problem + - Thanks to [Gavin Davies][pear-boxgav] for the patch +- Fixed bug #18628 : Generic.Files.LineLength gives incorrect results with Windows line-endings +- Fixed bug #18633 : CSS Tokenizer doesn't replace T_LIST tokens inside some styles +- Fixed bug #18657 : anonymous functions wrongly indented +- Fixed bug #18670 : UpperCaseConstantNameSniff fails on dynamic retrieval of class constant +- Fixed bug #18709 : Code sniffer sniffs file if even if it's in --ignore + - Thanks to [Artem Lopata][@biozshock] for the patch +- Fixed bug #18762 : Incorrect handling of define and constant in UpperCaseConstantNameSniff + - Thanks to [Thomas Baker][pear-bakert] for the patch +- Fixed bug #18769 : CSS Tokenizer doesn't replace T_BREAK tokens inside some styles +- Fixed bug #18835 : Unreachable errors of inline returns of closure functions + - Thanks to [Patrick Schmidt][pear-woellchen] for the patch +- Fixed bug #18839 : Fix miscount of warnings in AbstractSniffUnitTest.php + - Thanks to [Sam Graham][@illusori] for the patch +- Fixed bug #18844 : Generic_Sniffs_CodeAnalysis_UnusedFunctionParameterSniff with empty body + - Thanks to [Dmitri Medvedev][pear-dvino] for the patch +- Fixed bug #18847 : Running Squiz_Sniffs_Classes_ClassDeclarationSniff results in PHP notice +- Fixed bug #18868 : jslint+rhino: errors/warnings not detected + - Thanks to [Christian Weiske][@cweiske] for the patch +- Fixed bug #18879 : phpcs-svn-pre-commit requires escapeshellarg + - Thanks to [Bjorn Katuin][pear-bjorn] for the patch +- Fixed bug #18951 : weird behaviour with closures and multi-line use () params + +## 1.3.0 - 2011-03-17 +### Changed +- Add a new token T_CLOSURE that replaces T_FUNCTION if the function keyword is anonymous +- Many Squiz sniffs no longer report errors when checking closures; they are now ignored +- Fixed some error messages in PEAR MultiLineConditionSniff that were not using placeholders for message data +- AbstractVariableSniff now correctly finds variable names wrapped with curly braces inside double quoted strings +- PEAR FunctionDeclarationSniff now ignores arrays in argument default values when checking multi-line declarations + +### Fixed +- Fixed bug #18200 : Using custom named ruleset file as standard no longer works +- Fixed bug #18196 : PEAR MultiLineCondition.SpaceBeforeOpenBrace not consistent with newline chars +- Fixed bug #18204 : FunctionCommentThrowTag picks wrong exception type when throwing function call +- Fixed bug #18222 : Add __invoke method to PEAR standard +- Fixed bug #18235 : Invalid error generation in Squiz.Commenting.FunctionCommentThrowTag +- Fixed bug #18250 : --standard with relative path skips Standards' "implicit" sniffs +- Fixed bug #18274 : Multi-line IF and function call indent rules conflict +- Fixed bug #18282 : Squiz doesn't handle final keyword before function comments + - Thanks to [Dave Perrett][pear-recurser] for the patch +- Fixed bug #18336 : Function isUnderscoreName gives php notices + +## 1.3.0RC2 - 2011-01-14 +### Changed +- You can now print multiple reports for each run and print each to the screen or a file (request #12434) + - Format is --report-[report][=file] (e.g., --report-xml=out.xml) + - Printing to screen is done by leaving [file] empty (e.g., --report-xml) + - Multiple reports can be specified in this way (e.g., --report-summary --report-xml=out.xml) + - The standard --report and --report-file command line arguments are unchanged +- Added -d command line argument to set php.ini settings while running (request #17244) + - Usage is: phpcs -d memory_limit=32M -d ... + - Thanks to [Ben Selby][@benmatselby] for the patch +- Added -p command line argument to show progress during a run + - Dot means pass, E means errors found, W means only warnings found and S means skipped file + - Particularly good for runs where you are checking more than 100 files + - Enable by default with --config-set show_progress 1 + - Will not print anything if you are already printing verbose output + - This has caused a big change in the way PHP_CodeSniffer processes files (API changes around processing) +- You can now add exclude rules for individual sniffs or error messages (request #17903) + - Only available when using a ruleset.xml file to specify rules + - Uses the same exclude-pattern tags as normal but allows them inside rule tags +- Using the -vvv option will now print a list of sniffs executed for each file and how long they took to process +- Added Generic ClosureLinterSniff to run Google's gjslint over your JS files +- The XML and CSV reports now include the severity of the error (request #18165) + - The Severity column in the CSV report has been renamed to Type, and a new Severity column added for this +- Fixed issue with Squiz FunctionCommentSniff reporting incorrect type hint when default value uses namespace + - Thanks to Anti Veeranna for the patch +- Generic FileLengthSniff now uses iconv_strlen to check line length if an encoding is specified (request #14237) +- Generic UnnecessaryStringConcatSniff now allows strings to be combined to form a PHP open or close tag +- Squiz SwitchDeclarationSniff no longer reports indentation errors for BREAK statements inside IF conditions +- Interactive mode now always prints the full error report (ignores command line) +- Improved regular expression detection in JavaScript files + - Added new T_TYPEOF token that can be used to target the typeof JS operator + - Fixes bug #17611 : Regular expression tokens not recognised +- Squiz ScopeIndentSniff removed + - Squiz standard no longer requires additional indents between ob_* methods + - Also removed Squiz OutputBufferingIndentSniff that was checking the same thing +- PHP_CodeSniffer_File::getMemberProperties() performance improved significantly + - Improves performance of Squiz ValidVariableNameSniff significantly +- Squiz OperatorSpacingSniff performance improved significantly +- Squiz NonExecutableCodeSniff performance improved significantly + - Will throw duplicate errors in some cases now, but these should be rare +- MySource IncludeSystemSniff performance improved significantly +- MySource JoinStringsSniff no longer reports an error when using join() on a named JS array +- Warnings are now reported for each file when they cannot be opened instead of stopping the script + - Hide warnings with the -n command line argument + - Can override the warnings using the code Internal.DetectLineEndings + +### Fixed +- Fixed bug #17693 : issue with pre-commit hook script with filenames that start with v +- Fixed bug #17860 : isReference function fails with references in array + - Thanks to [Lincoln Maskey][pear-ljmaskey] for the patch +- Fixed bug #17902 : Cannot run tests when tests are symlinked into tests dir + - Thanks to [Matt Button][@BRMatt] for the patch +- Fixed bug #17928 : Improve error message for Generic_Sniffs_PHP_UpperCaseConstantSniff + - Thanks to [Stefano Kowalke][@Konafets] for the patch +- Fixed bug #18039 : JS Tokenizer crash when ] is last character in file +- Fixed bug #18047 : Incorrect handling of namespace aliases as constants + - Thanks to [Dmitri Medvedev][pear-dvino] for the patch +- Fixed bug #18072 : Impossible to exclude path from processing when symlinked +- Fixed bug #18073 : Squiz.PHP.NonExecutableCode fault +- Fixed bug #18117 : PEAR coding standard: Method constructor not sniffed as a function +- Fixed bug #18135 : Generic FunctionCallArgumentSpacingSniff reports function declaration errors +- Fixed bug #18140 : Generic scope indent in exact mode: strange expected/found values for switch +- Fixed bug #18145 : Sniffs are not loaded for custom ruleset file + - Thanks to [Scott McCammon][pear-mccammos] for the patch +- Fixed bug #18152 : While and do-while with AbstractPatternSniff +- Fixed bug #18191 : Squiz.PHP.LowercasePHPFunctions does not work with new Date() +- Fixed bug #18193 : CodeSniffer doesn't reconize CR (\r) line endings + +## 1.3.0RC1 - 2010-09-03 +### Changed +- Added exclude pattern support to ruleset.xml file so you can specify ignore patterns in a standard (request #17683) + - Use new exclude-pattern tags to include the ignore rules into your ruleset.xml file + - See CodeSniffer/Standards/PHPCS/ruleset.xml for an example +- Added new --encoding command line argument to specify the encoding of the files being checked + - When set to utf-8, stops the XML-based reports from double-encoding + - When set to something else, helps the XML-based reports encode to utf-8 + - Default value is iso-8859-1 but can be changed with --config-set encoding [value] +- The report is no longer printed to screen when using the --report-file command line option (request #17467) + - If you want to print it to screen as well, use the -v command line argument +- The SVN and GIT blame reports now also show percentage of reported errors per author (request #17606) + - Thanks to [Ben Selby][@benmatselby] for the patch +- Updated the SVN pre-commit hook to work with the new severity levels feature +- Generic SubversionPropertiesSniff now allows properties to have NULL values (request #17682) + - A null value indicates that the property should exist but the value should not be checked +- Generic UpperCaseConstantName Sniff now longer complains about the PHPUnit_MAIN_METHOD constant (request #17798) +- Squiz FileComment sniff now checks JS files as well as PHP files +- Squiz FunctionCommentSniff now supports namespaces in type hints + +### Fixed +- Fixed a problem in Squiz OutputBufferingIndentSniff where block comments were reported as not indented +- Fixed bug #17092 : Problems with utf8_encode and htmlspecialchars with non-ascii chars + - Use the new --encoding=utf-8 command line argument if your files are utf-8 encoded +- Fixed bug #17629 : PHP_CodeSniffer_Tokens::$booleanOperators missing T_LOGICAL_XOR + - Thanks to [Matthew Turland][@elazar] for the patch +- Fixed bug #17699 : Fatal error generating code coverage with PHPUnit 5.3.0RC1 +- Fixed bug #17718 : Namespace 'use' statement: used global class name is recognized as constant +- Fixed bug #17734 : Generic SubversionPropertiesSniff complains on non SVN files +- Fixed bug #17742 : EmbeddedPhpSniff reacts negatively to file without closing php tag +- Fixed bug #17823 : Notice: Please no longer include PHPUnit/Framework.php + +## 1.3.0a1 - 2010-07-15 +### Changed +- All CodingStandard.php files have been replaced by ruleset.xml files + - Custom standards will need to be converted over to this new format to continue working +- You can specify a path to your own custom ruleset.xml file by using the --standard command line arg + - e.g., phpcs --standard=/path/to/my/ruleset.xml +- Added a new report type --report=gitblame to show how many errors and warnings were committed by each author + - Has the same functionality as the svnblame report + - Thanks to [Ben Selby][@benmatselby] for the patch +- A new token type T_DOLLAR has been added to allow you to sniff for variable variables (feature request #17095) + - Thanks to [Ian Young][pear-youngian] for the patch +- JS tokenizer now supports T_POWER (^) and T_MOD_EQUAL (%=) tokens (feature request #17441) +- If you have PHP_Timer installed, you'll now get a time/memory summary at the end of a script run + - Only happens when printing reports that are designed to be read on the command line +- Added Generic DeprecatedFunctionsSniff to warn about the use of deprecated functions (feature request #16694) + - Thanks to [Sebastian Bergmann][@sebastianbergmann] for the patch +- Added Squiz LogicalOperatorSniff to ensure that logical operators are surrounded by single spaces +- Added MySource ChannelExceptionSniff to ensure action files only throw ChannelException +- Added new method getClassProperties() for sniffs to use to determine if a class is abstract and/or final + - Thanks to [Christian Kaps][@akkie] for the patch +- Generic UpperCaseConstantSniff no longer throws errors about namespaces + - Thanks to [Christian Kaps][@akkie] for the patch +- Squiz OperatorBracketSniff now correctly checks value assignments in arrays +- Squiz LongConditionClosingCommentSniff now requires a comment for long CASE statements that use curly braces +- Squiz LongConditionClosingCommentSniff now requires an exact comment match on the brace +- MySource IncludeSystemSniff now ignores DOMDocument usage +- MySource IncludeSystemSniff no longer requires inclusion of systems that are being implemented +- Removed found and expected messages from Squiz ConcatenationSpacingSniff because they were messy and not helpful + +### Fixed +- Fixed a problem where Generic CodeAnalysisSniff could show warnings if checking multi-line strings +- Fixed error messages in Squiz ArrayDeclarationSniff reporting incorrect number of found and expected spaces +- Fixed bug #17048 : False positive in Squiz_WhiteSpace_ScopeKeywordSpacingSniff +- Fixed bug #17054 : phpcs more strict than PEAR CS regarding function parameter spacing +- Fixed bug #17096 : Notice: Undefined index: scope_condition in ScopeClosingBraceSniff.php + - Moved PEAR.Functions.FunctionCallArgumentSpacing to Generic.Functions.FunctionCallArgumentSpacing +- Fixed bug #17144 : Deprecated: Function eregi() is deprecated +- Fixed bug #17236 : PHP Warning due to token_get_all() in DoubleQuoteUsageSniff +- Fixed bug #17243 : Alternate Switch Syntax causes endless loop of Notices in SwitchDeclaration +- Fixed bug #17313 : Bug with switch case structure +- Fixed bug #17331 : Possible parse error: interfaces may not include member vars +- Fixed bug #17337 : CSS tokenizer fails on quotes urls +- Fixed bug #17420 : Uncaught exception when comment before function brace +- Fixed bug #17503 : closures formatting is not supported + +## 1.2.2 - 2010-01-27 +### Changed +- The core PHP_CodeSniffer_File methods now understand the concept of closures (feature request #16866) + - Thanks to [Christian Kaps][@akkie] for the sample code +- Sniffs can now specify violation codes for each error and warning they add + - Future versions will allow you to override messages and severities using these codes + - Specifying a code is optional, but will be required if you wish to support overriding +- All reports have been broken into separate classes + - Command line usage and report output remains the same + - Thanks to Gabriele Santini for the patch +- Added an interactive mode that can be enabled using the -a command line argument + - Scans files and stops when it finds a file with errors + - Waits for user input to recheck the file (hopefully you fixed the errors) or skip the file + - Useful for very large code bases where full rechecks take a while +- The reports now show the correct number of errors and warnings found +- The isCamelCaps method now allows numbers in class names +- The JS tokenizer now correctly identifies boolean and bitwise AND and OR tokens +- The JS tokenizer now correctly identifies regular expressions used in conditions +- PEAR ValidFunctionNameSniff now ignores closures +- Squiz standard now uses the PEAR setting of 85 chars for LineLengthSniff +- Squiz ControlStructureSpacingSniff now ensure there are no spaces around parentheses +- Squiz LongConditionClosingCommentSniff now checks for comments at the end of try/catch statements +- Squiz LongConditionClosingCommentSniff now checks validity of comments for short structures if they exist +- Squiz IncrementDecrementUsageSniff now has better checking to ensure it only looks at simple variable assignments +- Squiz PostStatementCommentSniff no longer throws errors for end function comments +- Squiz InlineCommentSniff no longer throws errors for end function comments +- Squiz OperatorBracketSniff now allows simple arithmetic operations in SWITCH conditions +- Squiz ValidFunctionNameSniff now ignores closures +- Squiz MethodScopeSniff now ignores closures +- Squiz ClosingDeclarationCommentSniff now ignores closures +- Squiz GlobalFunctionSniff now ignores closures +- Squiz DisallowComparisonAssignmentSniff now ignores the assigning of arrays +- Squiz DisallowObjectStringIndexSniff now allows indexes that contain dots and reserved words +- Squiz standard now throws nesting level and cyclomatic complexity errors at much higher levels +- Squiz CommentedOutCodeSniff now ignores common comment framing characters +- Squiz ClassCommentSniff now ensures the open comment tag is the only content on the first line +- Squiz FileCommentSniff now ensures the open comment tag is the only content on the first line +- Squiz FunctionCommentSniff now ensures the open comment tag is the only content on the first line +- Squiz VariableCommentSniff now ensures the open comment tag is the only content on the first line +- Squiz NonExecutableCodeSniff now warns about empty return statements that are not required +- Removed ForbiddenStylesSniff from Squiz standard + - It is now in in the MySource standard as BrowserSpecificStylesSniff + - New BrowserSpecificStylesSniff ignores files with browser-specific suffixes +- MySource IncludeSystemSniff no longer throws errors when extending the Exception class +- MySource IncludeSystemSniff no longer throws errors for the abstract widget class +- MySource IncludeSystemSniff and UnusedSystemSniff now allow includes inside IF statements +- MySource IncludeSystemSniff no longer throws errors for included widgets inside methods +- MySource GetRequestDataSniff now throws errors for using $_FILES +- MySource CreateWidgetTypeCallbackSniff now allows return statements in nested functions +- MySource DisallowSelfActionsSniff now ignores abstract classes + +### Fixed +- Fixed a problem with the SVN pre-commit hook for PHP versions without vertical whitespace regex support +- Fixed bug #16740 : False positives for heredoc strings and unused parameter sniff +- Fixed bug #16794 : ValidLogicalOperatorsSniff doesn't report operators not in lowercase +- Fixed bug #16804 : Report filename is shortened too much +- Fixed bug #16821 : Bug in Squiz_Sniffs_WhiteSpace_OperatorSpacingSniff + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #16836 : Notice raised when using semicolon to open case +- Fixed bug #16855 : Generic standard sniffs incorrectly for define() method +- Fixed bug #16865 : Two bugs in Squiz_Sniffs_WhiteSpace_OperatorSpacingSniff + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #16902 : Inline If Declaration bug +- Fixed bug #16960 : False positive for late static binding in Squiz/ScopeKeywordSpacingSniff + - Thanks to [Jakub Tománek][pear-thezero] for the patch +- Fixed bug #16976 : The phpcs attempts to process symbolic links that don't resolve to files +- Fixed bug #17017 : Including one file in the files sniffed alters errors reported for another file + +## 1.2.1 - 2009-11-17 +### Changed +- Added a new report type --report=svnblame to show how many errors and warnings were committed by each author + - Also shows the percentage of their code that are errors and warnings + - Requires you to have the SVN command in your path + - Make sure SVN is storing usernames and passwords (if required) or you will need to enter them for each file + - You can also use the -s command line argument to see the different types of errors authors are committing + - You can use the -v command line argument to see all authors, even if they have no errors or warnings +- Added a new command line argument --report-width to allow you to set the column width of screen reports + - Reports wont accept values less than 70 or else they get too small + - Can also be set via a config var: phpcs --config-set report_width 100 +- You can now get PHP_CodeSniffer to ignore a whole file by adding @codingStandardsIgnoreFile in the content + - If you put it in the first two lines the file wont even be tokenized, so it will be much quicker +- Reports now print their file lists in alphabetical order +- PEAR FunctionDeclarationSniff now reports error for incorrect closing bracket placement in multi-line definitions +- Added Generic CallTimePassByReferenceSniff to prohibit the passing of variables into functions by reference + - Thanks to Florian Grandel for the contribution +- Added Squiz DisallowComparisonAssignmentSniff to ban the assignment of comparison values to a variable +- Added Squiz DuplicateStyleDefinitionSniff to check for duplicate CSS styles in a single class block +- Squiz ArrayDeclarationSniff no longer checks the case of array indexes because that is not its job +- Squiz PostStatementCommentSniff now allows end comments for class member functions +- Squiz InlineCommentSniff now supports the checking of JS files +- MySource CreateWidgetTypeCallbackSniff now allows the callback to be passed to another function +- MySource CreateWidgetTypeCallbackSniff now correctly ignores callbacks used inside conditions +- Generic MultipleStatementAlignmentSniff now enforces a single space before equals sign if max padding is reached +- Fixed a problem in the JS tokenizer where regular expressions containing \// were not converted correctly +- Fixed a problem tokenizing CSS files where multiple ID targets on a line would look like comments +- Fixed a problem tokenizing CSS files where class names containing a colon looked like style definitions +- Fixed a problem tokenizing CSS files when style statements had empty url() calls +- Fixed a problem tokenizing CSS colours with the letter E in first half of the code +- Squiz ColonSpacingSniff now ensures it is only checking style definitions in CSS files and not class names +- Squiz DisallowComparisonAssignmentSniff no longer reports errors when assigning the return value of a function +- CSS tokenizer now correctly supports multi-line comments +- When only the case of var names differ for function comments, the error now indicates the case is different + +### Fixed +- Fixed an issue with Generic UnnecessaryStringConcatSniff where it incorrectly suggested removing a concat +- Fixed bug #16530 : ScopeIndentSniff reports false positive +- Fixed bug #16533 : Duplicate errors and warnings +- Fixed bug #16563 : Check file extensions problem in phpcs-svn-pre-commit + - Thanks to [Kaijung Chen][pear-et3w503] for the patch +- Fixed bug #16592 : Object operator indentation incorrect when first operator is on a new line +- Fixed bug #16641 : Notice output +- Fixed bug #16682 : Squiz_Sniffs_Strings_DoubleQuoteUsageSniff reports string "\0" as invalid +- Fixed bug #16683 : Typing error in PHP_CodeSniffer_CommentParser_AbstractParser +- Fixed bug #16684 : Bug in Squiz_Sniffs_PHP_NonExecutableCodeSniff +- Fixed bug #16692 : Spaces in paths in Squiz_Sniffs_Debug_JavaScriptLintSniff + - Thanks to [Jaroslav Hanslík][@kukulich] for the patch +- Fixed bug #16696 : Spelling error in MultiLineConditionSniff +- Fixed bug #16697 : MultiLineConditionSniff incorrect result with inline IF +- Fixed bug #16698 : Notice in JavaScript Tokenizer +- Fixed bug #16736 : Multi-files sniffs aren't processed when FILE is a single directory + - Thanks to [Alexey Shein][pear-conf] for the patch +- Fixed bug #16792 : Bug in Generic_Sniffs_PHP_ForbiddenFunctionsSniff + +## 1.2.0 - 2009-08-17 +### Changed +- Installed standards are now favoured over custom standards when using the cmd line arg with relative paths +- Unit tests now use a lot less memory while running +- Squiz standard now uses Generic EmptyStatementSniff but throws errors instead of warnings +- Squiz standard now uses Generic UnusedFunctionParameterSniff +- Removed unused ValidArrayIndexNameSniff from the Squiz standard + +### Fixed +- Fixed bug #16424 : SubversionPropertiesSniff print PHP Warning +- Fixed bug #16450 : Constant PHP_CODESNIFFER_VERBOSITY already defined (unit tests) +- Fixed bug #16453 : function declaration long line splitted error +- Fixed bug #16482 : phpcs-svn-pre-commit ignores extensions parameter + +## 1.2.0RC3 - 2009-07-07 +### Changed +- You can now use @codingStandardsIgnoreStart and @...End comments to suppress messages (feature request #14002) +- A warning is now included for files without any code when short_open_tag is set to Off (feature request #12952) +- You can now use relative paths to your custom standards with the --standard cmd line arg (feature request #14967) +- You can now override magic methods and functions in PEAR ValidFunctionNameSniff (feature request #15830) +- MySource IncludeSystemSniff now recognises widget action classes +- MySource IncludeSystemSniff now knows about unit test classes and changes rules accordingly + +## 1.2.0RC2 - 2009-05-25 +### Changed +- Test suite can now be run using the full path to AllTests.php (feature request #16179) + +### Fixed +- Fixed bug #15980 : PHP_CodeSniffer change php current directory + - Thanks to [Dolly Aswin Harahap][pear-dollyaswin] for the patch +- Fixed bug #16001 : Notice triggered +- Fixed bug #16054 : phpcs-svn-pre-commit not showing any errors +- Fixed bug #16071 : Fatal error: Uncaught PHP_CodeSniffer_Exception +- Fixed bug #16170 : Undefined Offset -1 in MultiLineConditionSniff.php on line 68 +- Fixed bug #16175 : Bug in Squiz-IncrementDecrementUsageSniff + +## 1.2.0RC1 - 2009-03-09 +### Changed +- Reports that are output to a file now include a trailing newline at the end of the file +- Fixed sniff names not shown in -vvv token processing output +- Added Generic SubversionPropertiesSniff to check that specific svn props are set for files + - Thanks to Jack Bates for the contribution +- The PHP version check can now be overridden in classes that extend PEAR FileCommentSniff + - Thanks to [Helgi Þormar Þorbjörnsson][@helgi] for the suggestion +- Added Generic ConstructorNameSniff to check for PHP4 constructor name usage + - Thanks to Leif Wickland for the contribution +- Squiz standard now supports multi-line function and condition sniffs from PEAR standard +- Squiz standard now uses Generic ConstructorNameSniff +- Added MySource GetRequestDataSniff to ensure REQUEST, GET and POST are not accessed directly +- Squiz OperatorBracketSniff now allows square brackets in simple unbracketed operations + +### Fixed +- Fixed the incorrect tokenizing of multi-line block comments in CSS files +- Fixed bug #15383 : Uncaught PHP_CodeSniffer_Exception +- Fixed bug #15408 : An unexpected exception has been caught: Undefined offset: 2 +- Fixed bug #15519 : Uncaught PHP_CodeSniffer_Exception +- Fixed bug #15624 : Pre-commit hook fails with PHP errors +- Fixed bug #15661 : Uncaught PHP_CodeSniffer_Exception +- Fixed bug #15722 : "declare(encoding = 'utf-8');" leads to "Missing file doc comment" +- Fixed bug #15910 : Object operator indention not calculated correctly + +## 1.2.0a1 - 2008-12-18 +### Changed +- PHP_CodeSniffer now has a CSS tokenizer for checking CSS files +- Added support for a new multi-file sniff that sniffs all processed files at once +- Added new output format --report=emacs to output errors using the emacs standard compile output format + - Thanks to Len Trigg for the contribution +- Reports can now be written to a file using the --report-file command line argument (feature request #14953) + - The report is also written to screen when using this argument +- The CheckStyle, CSV and XML reports now include a source for each error and warning (feature request #13242) + - A new report type --report=source can be used to show you the most common errors in your files +- Added new command line argument -s to show error sources in all reports +- Added new command line argument --sniffs to specify a list of sniffs to restrict checking to + - Uses the sniff source codes that are optionally displayed in reports +- Changed the max width of error lines from 80 to 79 chars to stop blank lines in the default windows cmd window +- PHP_CodeSniffer now has a token for an asperand (@ symbol) so sniffs can listen for them + - Thanks to Andy Brockhurst for the patch +- Added Generic DuplicateClassNameSniff that will warn if the same class name is used in multiple files + - Not currently used by any standard; more of a multi-file sniff sample than anything useful +- Added Generic NoSilencedErrorsSniff that warns if PHP errors are being silenced using the @ symbol + - Thanks to Andy Brockhurst for the contribution +- Added Generic UnnecessaryStringConcatSniff that checks for two strings being concatenated +- Added PEAR FunctionDeclarationSniff to enforce the new multi-line function declaration PEAR standard +- Added PEAR MultiLineAssignmentSniff to enforce the correct indentation of multi-line assignments +- Added PEAR MultiLineConditionSniff to enforce the new multi-line condition PEAR standard +- Added PEAR ObjectOperatorIndentSniff to enforce the new chained function call PEAR standard +- Added MySource DisallowSelfActionSniff to ban the use of self::method() calls in Action classes +- Added MySource DebugCodeSniff to ban the use of Debug::method() calls +- Added MySource CreateWidgetTypeCallback sniff to check callback usage in widget type create methods +- Added Squiz DisallowObjectStringIndexSniff that forces object dot notation in JavaScript files + - Thanks to [Sertan Danis][@sertand] for the contribution +- Added Squiz DiscouragedFunctionsSniff to warn when using debug functions +- Added Squiz PropertyLabelSniff to check whitespace around colons in JS property and label declarations +- Added Squiz DuplicatePropertySniff to check for duplicate property names in JS classes +- Added Squiz ColonSpacingSniff to check for spacing around colons in CSS style definitions +- Added Squiz SemicolonSpacingSniff to check for spacing around semicolons in CSS style definitions +- Added Squiz IndentationSniff to check for correct indentation of CSS files +- Added Squiz ColourDefinitionSniff to check that CSS colours are defined in uppercase and using shorthand +- Added Squiz EmptyStyleDefinitionSniff to check for CSS style definitions without content +- Added Squiz EmptyClassDefinitionSniff to check for CSS class definitions without content +- Added Squiz ClassDefinitionOpeningBraceSpaceSniff to check for spaces around opening brace of CSS class definitions +- Added Squiz ClassDefinitionClosingBraceSpaceSniff to check for a single blank line after CSS class definitions +- Added Squiz ClassDefinitionNameSpacingSniff to check for a blank lines inside CSS class definition names +- Added Squiz DisallowMultipleStyleDefinitionsSniff to check for multiple style definitions on a single line +- Added Squiz DuplicateClassDefinitionSniff to check for duplicate CSS class blocks that can be merged +- Added Squiz ForbiddenStylesSniff to check for usage of browser specific styles +- Added Squiz OpacitySniff to check for incorrect opacity values in CSS +- Added Squiz LowercaseStyleDefinitionSniff to check for styles that are not defined in lowercase +- Added Squiz MissingColonSniff to check for style definitions where the colon has been forgotten +- Added Squiz MultiLineFunctionDeclarationSniff to check that multi-line declarations contain one param per line +- Added Squiz JSLintSniff to check for JS errors using the jslint.js script through Rhino + - Set jslint path using phpcs --config-set jslint_path /path/to/jslint.js + - Set rhino path using phpcs --config-set rhino_path /path/to/rhino +- Added Generic TodoSniff that warns about comments that contain the word TODO +- Removed MultipleStatementAlignmentSniff from the PEAR standard as alignment is now optional +- Generic ForbiddenFunctionsSniff now has protected member var to specify if it should use errors or warnings +- Generic MultipleStatementAlignmentSniff now has correct error message if assignment is on a new line +- Generic MultipleStatementAlignmentSniff now has protected member var to allow it to ignore multi-line assignments +- Generic LineEndingsSniff now supports checking of JS files +- Generic LineEndingsSniff now supports checking of CSS files +- Generic DisallowTabIndentSniff now supports checking of CSS files +- Squiz DoubleQuoteUsageSniff now bans the use of variables in double quoted strings in favour of concatenation +- Squiz SuperfluousWhitespaceSniff now supports checking of JS files +- Squiz SuperfluousWhitespaceSniff now supports checking of CSS files +- Squiz DisallowInlineIfSniff now supports checking of JS files +- Squiz SemicolonSpacingSniff now supports checking of JS files +- Squiz PostStatementCommentSniff now supports checking of JS files +- Squiz FunctionOpeningBraceSpacingSniff now supports checking of JS files +- Squiz FunctionClosingBraceSpacingSniff now supports checking of JS files + - Empty JS functions must have their opening and closing braces next to each other +- Squiz ControlStructureSpacingSniff now supports checking of JS files +- Squiz LongConditionClosingCommentSniff now supports checking of JS files +- Squiz OperatorSpacingSniff now supports checking of JS files +- Squiz SwitchDeclarationSniff now supports checking of JS files +- Squiz CommentedOutCodeSniff now supports checking of CSS files +- Squiz DisallowSizeFunctionsInLoopsSniff now supports checking of JS files for the use of object.length +- Squiz DisallowSizeFunctionsInLoopsSniff no longer complains about size functions outside of the FOR condition +- Squiz ControlStructureSpacingSniff now bans blank lines at the end of a control structure +- Squiz ForLoopDeclarationSniff no longer throws errors for JS FOR loops without semicolons +- Squiz MultipleStatementAlignmentSniff no longer throws errors if a statement would take more than 8 spaces to align +- Squiz standard now uses Generic TodoSniff +- Squiz standard now uses Generic UnnecessaryStringConcatSniff +- Squiz standard now uses PEAR MultiLineAssignmentSniff +- Squiz standard now uses PEAR MultiLineConditionSniff +- Zend standard now uses OpeningFunctionBraceBsdAllmanSniff (feature request #14647) +- MySource JoinStringsSniff now bans the use of inline array joins and suggests the + operator +- Fixed incorrect errors that can be generated from abstract scope sniffs when moving to a new file +- Core tokenizer now matches orphaned curly braces in the same way as square brackets +- Whitespace tokens at the end of JS files are now added to the token stack +- JavaScript tokenizer now identifies properties and labels as new token types +- JavaScript tokenizer now identifies object definitions as a new token type and matches curly braces for them +- JavaScript tokenizer now identifies DIV_EQUAL and MUL_EQUAL tokens +- Improved regular expression detection in the JavaScript tokenizer +- Improve AbstractPatternSniff support so it can listen for any token type, not just weighted tokens + +### Fixed +- Fixed Squiz DoubleQuoteUsageSniff so it works correctly with short_open_tag=Off +- Fixed bug #14409 : Output of warnings to log file +- Fixed bug #14520 : Notice: Undefined offset: 1 in /usr/share/php/PHP/CodeSniffer/File.php on line +- Fixed bug #14637 : Call to processUnknownArguments() misses second parameter $pos + - Thanks to [Peter Buri][pear-burci] for the patch +- Fixed bug #14889 : Lack of clarity: licence or license +- Fixed bug #15008 : Nested Parentheses in Control Structure Sniffs +- Fixed bug #15091 : pre-commit hook attempts to sniff folders + - Thanks to [Bruce Weirdan][pear-weirdan] for the patch +- Fixed bug #15124 : AbstractParser.php uses deprecated split() function + - Thanks to [Sebastian Bergmann][@sebastianbergmann] for the patch +- Fixed bug #15188 : PHPCS vs HEREDOC strings +- Fixed bug #15231 : Notice: Uninitialized string offset: 0 in FileCommentSniff.php on line 555 +- Fixed bug #15336 : Notice: Undefined offset: 2 in /usr/share/php/PHP/CodeSniffer/File.php on line + +## 1.1.0 - 2008-07-14 +### Changed +- PEAR FileCommentSniff now allows tag orders to be overridden in child classes + - Thanks to Jeff Hodsdon for the patch +- Added Generic DisallowMultipleStatementsSniff to ensure there is only one statement per line +- Squiz standard now uses DisallowMultipleStatementsSniff + +### Fixed +- Fixed error in Zend ValidVariableNameSniff when checking vars in form: $class->{$var} +- Fixed bug #14077 : Fatal error: Uncaught PHP_CodeSniffer_Exception: $stackPtr is not a class member +- Fixed bug #14168 : Global Function -> Static Method and __autoload() +- Fixed bug #14238 : Line length not checked at last line of a file +- Fixed bug #14249 : wrong detection of scope_opener +- Fixed bug #14250 : ArrayDeclarationSniff emit warnings at malformed array +- Fixed bug #14251 : --extensions option doesn't work + +## 1.1.0RC3 - 2008-07-03 +### Changed +- PEAR FileCommentSniff now allows tag orders to be overridden in child classes + - Thanks to Jeff Hodsdon for the patch +- Added Generic DisallowMultipleStatementsSniff to ensure there is only one statement per line +- Squiz standard now uses DisallowMultipleStatementsSniff + +### Fixed +- Fixed error in Zend ValidVariableNameSniff when checking vars in form: $class->{$var} +- Fixed bug #14077 : Fatal error: Uncaught PHP_CodeSniffer_Exception: $stackPtr is not a class member +- Fixed bug #14168 : Global Function -> Static Method and __autoload() +- Fixed bug #14238 : Line length not checked at last line of a file +- Fixed bug #14249 : wrong detection of scope_opener +- Fixed bug #14250 : ArrayDeclarationSniff emit warnings at malformed array +- Fixed bug #14251 : --extensions option doesn't work + +## 1.1.0RC2 - 2008-06-13 +### Changed +- Permission denied errors now stop script execution but still display current errors (feature request #14076) +- Added Squiz ValidArrayIndexNameSniff to ensure array indexes do not use camel case +- Squiz ArrayDeclarationSniff now ensures arrays are not declared with camel case index values +- PEAR ValidVariableNameSniff now alerts about a possible parse error for member vars inside an interface + +### Fixed +- Fixed bug #13921 : js parsing fails for comments on last line of file +- Fixed bug #13922 : crash in case of malformed (but tokenized) php file + - PEAR and Squiz ClassDeclarationSniff now throw warnings for possible parse errors + - Squiz ValidClassNameSniff now throws warning for possible parse errors + - Squiz ClosingDeclarationCommentSniff now throws additional warnings for parse errors + +## 1.1.0RC1 - 2008-05-13 +### Changed +- Added support for multiple tokenizers so PHP_CodeSniffer can check more than just PHP files + - PHP_CodeSniffer now has a JS tokenizer for checking JavaScript files + - Sniffs need to be updated to work with additional tokenizers, or new sniffs written for them +- phpcs now exits with status 2 if the tokenizer extension has been disabled (feature request #13269) +- Added scripts/phpcs-svn-pre-commit that can be used as an SVN pre-commit hook + - Also reworked the way the phpcs script works to make it easier to wrap it with other functionality + - Thanks to Jack Bates for the contribution +- Fixed error in phpcs error message when a supplied file does not exist +- Fixed a cosmetic error in AbstractPatternSniff where the "found" string was missing some content +- Added sniffs that implement part of the PMD rule catalog to the Generic standard + - Thanks to [Manuel Pichler][@manuelpichler] for the contribution of all these sniffs. +- Squiz FunctionCommentThrowTagSniff no longer throws errors for function that only throw variables +- Generic ScopeIndentSniff now has private member to enforce exact indent matching +- Replaced Squiz DisallowCountInLoopsSniff with Squiz DisallowSizeFunctionsInLoopsSniff + - Thanks to Jan Miczaika for the sniff +- Squiz BlockCommentSniff now checks inline doc block comments +- Squiz InlineCommentSniff now checks inline doc block comments +- Squiz BlockCommentSniff now checks for no blank line before first comment in a function +- Squiz DocCommentAlignmentSniff now ignores inline doc block comments +- Squiz ControlStructureSpacingSniff now ensures no blank lines at the start of control structures +- Squiz ControlStructureSpacingSniff now ensures no blank lines between control structure closing braces +- Squiz IncrementDecrementUsageSniff now ensures inc/dec ops are bracketed in string concats +- Squiz IncrementDecrementUsageSniff now ensures inc/dec ops are not used in arithmetic operations +- Squiz FunctionCommentSniff no longer throws errors if return value is mixed but function returns void somewhere +- Squiz OperatorBracketSniff no allows function call brackets to count as operator brackets +- Squiz DoubleQuoteUsageSniff now supports \x \f and \v (feature request #13365) +- Squiz ComparisonOperatorUsageSniff now supports JS files +- Squiz ControlSignatureSniff now supports JS files +- Squiz ForLoopDeclarationSniff now supports JS files +- Squiz OperatorBracketSniff now supports JS files +- Squiz InlineControlStructureSniff now supports JS files +- Generic LowerCaseConstantSniff now supports JS files +- Generic DisallowTabIndentSniff now supports JS files +- Generic MultipleStatementAlignmentSniff now supports JS files +- Added Squiz ObjectMemberCommaSniff to ensure the last member of a JS object is not followed by a comma +- Added Squiz ConstantCaseSniff to ensure the PHP constants are uppercase and JS lowercase +- Added Squiz JavaScriptLintSniff to check JS files with JSL + - Set path using phpcs --config-set jsl_path /path/to/jsl +- Added MySource FirebugConsoleSniff to ban the use of "console" for JS variable and function names +- Added MySource JoinStringsSniff to enforce the use of join() to concatenate JS strings +- Added MySource AssignThisSniff to ensure this is only assigned to a var called self +- Added MySource DisallowNewWidgetSniff to ban manual creation of widget objects +- Removed warning shown in Zend CodeAnalyzerSniff when the ZCA path is not set + +### Fixed +- Fixed error in Squiz ValidVariableNameSniff when checking vars in the form $obj->$var +- Fixed error in Squiz DisallowMultipleAssignmentsSniff when checking vars in the form $obj->$var +- Fixed error in Squiz InlineCommentSniff where comments for class constants were seen as inline +- Fixed error in Squiz BlockCommentSniff where comments for class constants were not ignored +- Fixed error in Squiz OperatorBracketSniff where negative numbers were ignored during comparisons +- Fixed error in Squiz FunctionSpacingSniff where functions after member vars reported incorrect spacing +- Fixed bug #13062 : Interface comments aren't handled in PEAR standard + - Thanks to [Manuel Pichler][@manuelpichler] for the path +- Fixed bug #13119 : php minimum requirement need to be fix +- Fixed bug #13156 : Bug in Squiz_Sniffs_PHP_NonExecutableCodeSniff +- Fixed bug #13158 : Strange behaviour in AbstractPatternSniff +- Fixed bug #13169 : Undefined variables +- Fixed bug #13178 : Catch exception in File.php +- Fixed bug #13254 : Notices output in checkstyle report causes XML issues +- Fixed bug #13446 : crash with src of phpMyAdmin + - Thanks to [Manuel Pichler][@manuelpichler] for the path + +## 1.0.1a1 - 2008-04-21 +### Changed +- Fixed error in PEAR ValidClassNameSniff when checking class names with double underscores +- Moved Squiz InlineControlStructureSniff into Generic standard +- PEAR standard now throws warnings for inline control structures +- Squiz OutputBufferingIndentSniff now ignores the indentation of inline HTML +- MySource IncludeSystemSniff now ignores usage of ZipArchive +- Removed "function" from error messages for Generic function brace sniffs (feature request #13820) +- Generic UpperCaseConstantSniff no longer throws errors for declare(ticks = ...) + - Thanks to Josh Snyder for the patch +- Squiz ClosingDeclarationCommentSniff and AbstractVariableSniff now throw warnings for possible parse errors + +### Fixed +- Fixed bug #13827 : AbstractVariableSniff throws "undefined index" +- Fixed bug #13846 : Bug in Squiz.NonExecutableCodeSniff +- Fixed bug #13849 : infinite loop in PHP_CodeSniffer_File::findNext() + +## 1.0.1 - 2008-02-04 +### Changed +- Squiz ArrayDeclarationSniff now throws error if the array keyword is followed by a space +- Squiz ArrayDeclarationSniff now throws error for empty multi-line arrays +- Squiz ArrayDeclarationSniff now throws error for multi-line arrays with a single value +- Squiz DocCommentAlignmentSniff now checks for a single space before tags inside docblocks +- Squiz ForbiddenFunctionsSniff now disallows is_null() to force use of (=== NULL) instead +- Squiz VariableCommentSniff now continues throwing errors after the first one is found +- Squiz SuperfluousWhitespaceSniff now throws errors for multiple blank lines inside functions +- MySource IncludedSystemSniff now checks extended class names +- MySource UnusedSystemSniff now checks extended and implemented class names +- MySource IncludedSystemSniff now supports includeWidget() +- MySource UnusedSystemSniff now supports includeWidget() +- Added PEAR ValidVariableNameSniff to check that only private member vars are prefixed with an underscore +- Added Squiz DisallowCountInLoopsSniff to check for the use of count() in FOR and WHILE loop conditions +- Added MySource UnusedSystemSniff to check for included classes that are never used + +### Fixed +- Fixed a problem that caused the parentheses map to sometimes contain incorrect values +- Fixed bug #12767 : Cant run phpcs from dir with PEAR subdir +- Fixed bug #12773 : Reserved variables are not detected in strings + - Thanks to [Wilfried Loche][pear-wloche] for the patch +- Fixed bug #12832 : Tab to space conversion does not work +- Fixed bug #12888 : extra space indentation = Notice: Uninitialized string offset... +- Fixed bug #12909 : Default generateDocs function does not work under linux + - Thanks to [Paul Smith][pear-thing2b] for the patch +- Fixed bug #12957 : PHP 5.3 magic method __callStatic + - Thanks to [Manuel Pichler][@manuelpichler] for the patch + +## 1.0.0 - 2007-12-21 +### Changed +- You can now specify the full path to a coding standard on the command line (feature request #11886) + - This allows you to use standards that are stored outside of PHP_CodeSniffer's own Standard dir + - You can also specify full paths in the CodingStandard.php include and exclude methods + - Classes, dirs and files need to be names as if the standard was part of PHP_CodeSniffer + - Thanks to Dirk Thomas for the doc generator patch and testing +- Modified the scope map to keep checking after 3 lines for some tokens (feature request #12561) + - Those tokens that must have an opener (like T_CLASS) now keep looking until EOF + - Other tokens (like T_FUNCTION) still stop after 3 lines for performance +- You can now escape commas in ignore patterns so they can be matched in file names + - Thanks to [Carsten Wiedmann][pear-cwiedmann] for the patch +- Config data is now cached in a global var so the file system is not hit so often + - You can also set config data temporarily for the script if you are using your own external script + - Pass TRUE as the third argument to PHP_CodeSniffer::setConfigData() +- PEAR ClassDeclarationSniff no longer throws errors for multi-line class declarations +- Squiz ClassDeclarationSniff now ensures there is one blank line after a class closing brace +- Squiz ClassDeclarationSniff now throws errors for a missing end PHP tag after the end class tag +- Squiz IncrementDecrementUsageSniff no longer throws errors when -= and += are being used with vars +- Squiz SwitchDeclarationSniff now throws errors for switch statements that do not contain a case statement + - Thanks to [Sertan Danis][@sertand] for the patch +- MySource IncludeSystemSniff no longer throws errors for the Util package + +### Fixed +- Fixed bug #12621 : "space after AS" check is wrong + - Thanks to [Satoshi Oikawa][pear-renoiv] for the patch +- Fixed bug #12645 : error message is wrong + - Thanks to [Satoshi Oikawa][pear-renoiv] for the patch +- Fixed bug #12651 : Increment/Decrement Operators Usage at -1 + +## 1.0.0RC3 - 2007-11-30 +### Changed +- Added new command line argument --tab-width that will convert tabs to spaces before testing + - This allows you to use the existing sniffs that check for spaces even when you use tabs + - Can also be set via a config var: phpcs --config-set tab_width 4 + - A value of zero (the default) tells PHP_CodeSniffer not to replace tabs with spaces +- You can now change the default report format from "full" to something else + - Run: phpcs --config-set report_format [format] +- Improved performance by optimising the way the scope map is created during tokenising +- Added new Squiz DisallowInlineIfSniff to disallow the usage of inline IF statements +- Fixed incorrect errors being thrown for nested switches in Squiz SwitchDeclarationSniff +- PEAR FunctionCommentSniff no longer complains about missing comments for @throws tags +- PEAR FunctionCommentSniff now throws error for missing exception class name for @throws tags +- PHP_CodeSniffer_File::isReference() now correctly returns for functions that return references +- Generic LineLengthSniff no longer warns about @version lines with CVS or SVN id tags +- Generic LineLengthSniff no longer warns about @license lines with long URLs +- Squiz FunctionCommentThrowTagSniff no longer complains about throwing variables +- Squiz ComparisonOperatorUsageSniff no longer throws incorrect errors for inline IF statements +- Squiz DisallowMultipleAssignmentsSniff no longer throws errors for assignments in inline IF statements + +### Fixed +- Fixed bug #12455 : CodeSniffer treats content inside heredoc as PHP code +- Fixed bug #12471 : Checkstyle report is broken +- Fixed bug #12476 : PHP4 destructors are reported as error +- Fixed bug #12513 : Checkstyle XML messages need to be utf8_encode()d + - Thanks to [Sebastian Bergmann][@sebastianbergmann] for the patch. +- Fixed bug #12517 : getNewlineAfter() and dos files + +## 1.0.0RC2 - 2007-11-14 +### Changed +- Added a new Checkstyle report format + - Like the current XML format but modified to look like Checkstyle output + - Thanks to [Manuel Pichler][@manuelpichler] for helping get the format correct +- You can now hide warnings by default + - Run: phpcs --config-set show_warnings 0 + - If warnings are hidden by default, use the new -w command line argument to override +- Added new command line argument --config-delete to delete a config value and revert to the default +- Improved overall performance by optimising tokenising and next/prev methods (feature request #12421) + - Thanks to [Christian Weiske][@cweiske] for the patch +- Added FunctionCallSignatureSniff to Squiz standard +- Added @subpackage support to file and class comment sniffs in PEAR standard (feature request #12382) + - Thanks to [Carsten Wiedmann][pear-cwiedmann] for the patch +- An error is now displayed if you use a PHP version less than 5.1.0 (feature request #12380) + - Thanks to [Carsten Wiedmann][pear-cwiedmann] for the patch +- phpcs now exits with status 2 if it receives invalid input (feature request #12380) + - This is distinct from status 1, which indicates errors or warnings were found +- Added new Squiz LanguageConstructSpacingSniff to throw errors for additional whitespace after echo etc. +- Removed Squiz ValidInterfaceNameSniff +- PEAR FunctionCommentSniff no longer complains about unknown tags + +### Fixed +- Fixed incorrect errors about missing function comments in PEAR FunctionCommentSniff +- Fixed incorrect function docblock detection in Squiz FunctionCommentSniff +- Fixed incorrect errors for list() in Squiz DisallowMultipleAssignmentsSniff +- Errors no longer thrown if control structure is followed by a CASE's BREAK in Squiz ControlStructureSpacingSniff +- Fixed bug #12368 : Autoloader cannot be found due to include_path override + - Thanks to [Richard Quadling][pear-rquadling] for the patch +- Fixed bug #12378 : equal sign alignments problem with while() + +## 1.0.0RC1 - 2007-11-01 +### Changed +- Main phpcs script can now be run from a CVS checkout without installing the package +- Added a new CSV report format + - Header row indicates what position each element is in + - Always use the header row to determine positions rather than assuming the format, as it may change +- XML and CSV report formats now contain information about which column the error occurred at + - Useful if you want to highlight the token that caused the error in a custom application +- Square bracket tokens now have bracket_opener and bracket_closer set +- Added new Squiz SemicolonSpacingSniff to throw errors if whitespace is found before a semicolon +- Added new Squiz ArrayBracketSpacingSniff to throw errors if whitespace is found around square brackets +- Added new Squiz ObjectOperatorSpacingSniff to throw errors if whitespace is found around object operators +- Added new Squiz DisallowMultipleAssignmentsSniff to throw errors if multiple assignments are on the same line +- Added new Squiz ScopeKeywordSpacingSniff to throw errors if there is not a single space after a scope modifier +- Added new Squiz ObjectInstantiationSniff to throw errors if new objects are not assigned to a variable +- Added new Squiz FunctionDuplicateArgumentSniff to throw errors if argument is declared multiple times in a function +- Added new Squiz FunctionOpeningBraceSpaceSniff to ensure there are no blank lines after a function open brace +- Added new Squiz CommentedOutCodeSniff to warn about comments that looks like they are commented out code blocks +- Added CyclomaticComplexitySniff to Squiz standard +- Added NestingLevelSniff to Squiz standard +- Squiz ForbiddenFunctionsSniff now recommends echo() instead of print() +- Squiz ValidLogicalOperatorsSniff now recommends ^ instead of xor +- Squiz SwitchDeclarationSniff now contains more checks + - A single space is required after the case keyword + - No space is allowed before the colon in a case or default statement + - All switch statements now require a default case + - Default case must contain a break statement + - Empty default case must contain a comment describing why the default is ignored + - Empty case statements are not allowed + - Case and default statements must not be followed by a blank line + - Break statements must be followed by a blank line or the closing brace + - There must be no blank line before a break statement +- Squiz standard is now using the PEAR IncludingFileSniff +- PEAR ClassCommentSniff no longer complains about unknown tags +- PEAR FileCommentSniff no longer complains about unknown tags +- PEAR FileCommentSniff now accepts multiple @copyright tags +- Squiz BlockCommentSniff now checks that comment starts with a capital letter +- Squiz InlineCommentSniff now has better checking to ensure comment starts with a capital letter +- Squiz ClassCommentSniff now checks that short and long comments start with a capital letter +- Squiz FunctionCommentSniff now checks that short, long and param comments start with a capital letter +- Squiz VariableCommentSniff now checks that short and long comments start with a capital letter + +### Fixed +- Fixed error with multi-token array indexes in Squiz ArrayDeclarationSniff +- Fixed error with checking shorthand IF statements without a semicolon in Squiz InlineIfDeclarationSniff +- Fixed error where constants used as default values in function declarations were seen as type hints +- Fixed bug #12316 : PEAR is no longer the default standard +- Fixed bug #12321 : wrong detection of missing function docblock + +## 0.9.0 - 2007-09-24 +### Changed +- Added a config system for setting config data across phpcs runs +- You can now change the default coding standard from PEAR to something else + - Run: phpcs --config-set default_standard [standard] +- Added new Zend coding standard to check code against the Zend Framework standards + - The complete standard is not yet implemented + - Specify --standard=Zend to use + - Thanks to Johann-Peter Hartmann for the contribution of some sniffs + - Thanks to Holger Kral for the Code Analyzer sniff + +## 0.8.0 - 2007-08-08 +### Changed +- Added new XML report format; --report=xml (feature request #11535) + - Thanks to [Brett Bieber][@saltybeagle] for the patch +- Added new command line argument --ignore to specify a list of files to skip (feature request #11556) +- Added PHPCS and MySource coding standards into the core install +- Scope map no longer gets confused by curly braces that act as string offsets +- Removed CodeSniffer/SniffException.php as it is no longer used +- Unit tests can now be run directly from a CVS checkout +- Made private vars and functions protected in PHP_CodeSniffer class so this package can be overridden +- Added new Metrics category to Generic coding standard + - Contains Cyclomatic Complexity and Nesting Level sniffs + - Thanks to Johann-Peter Hartmann for the contribution +- Added new Generic DisallowTabIndentSniff to throw errors if tabs are used for indentation (feature request #11738) + - PEAR and Squiz standards use this new sniff to throw more specific indentation errors +- Generic MultipleStatementAlignmentSniff has new private var to set a padding size limit (feature request #11555) +- Generic MultipleStatementAlignmentSniff can now handle assignments that span multiple lines (feature request #11561) +- Generic LineLengthSniff now has a max line length after which errors are thrown instead of warnings + - BC BREAK: Override the protected member var absoluteLineLimit and set it to zero in custom LineLength sniffs + - Thanks to Johann-Peter Hartmann for the contribution +- Comment sniff errors about incorrect tag orders are now more descriptive (feature request #11693) + +### Fixed +- Fixed bug #11473 : Invalid CamelCaps name when numbers used in names + +## 0.7.0 - 2007-07-02 +### Changed +- BC BREAK: EOL character is now auto-detected and used instead of hard-coded \n + - Pattern sniffs must now specify "EOL" instead of "\n" or "\r\n" to use auto-detection + - Please use $phpcsFile->eolChar to check for newlines instead of hard-coding "\n" or "\r\n" + - Comment parser classes now require you to pass $phpcsFile as an additional argument +- BC BREAK: Included and excluded sniffs now require .php extension + - Please update your coding standard classes and add ".php" to all sniff entries + - See CodeSniffer/Standards/PEAR/PEARCodingStandard.php for an example + +- Fixed error where including a directory of sniffs in a coding standard class did not work +- Coding standard classes can now specify a list of sniffs to exclude as well as include (feature request #11056) +- Two uppercase characters can now be placed side-by-side in class names in Squiz ValidClassNameSniff +- SVN tags now allowed in PEAR file doc blocks (feature request #11038) + - Thanks to [Torsten Roehr][pear-troehr] for the patch +- Private methods in commenting sniffs and comment parser are now protected (feature request #11087) +- Added Generic LineEndingsSniff to check the EOL character of a file +- PEAR standard now only throws one error per file for incorrect line endings (eg. /r/n) +- Command line arg -v now shows number of registered sniffs +- Command line arg -vvv now shows list of registered sniffs +- Squiz ControlStructureSpacingSniff no longer throws errors if the control structure is at the end of the script +- Squiz FunctionCommentSniff now throws error for "return void" if function has return statement +- Squiz FunctionCommentSniff now throws error for functions that return void but specify something else +- Squiz ValidVariableNameSniff now allows multiple uppercase letters in a row +- Squiz ForEachLoopDeclarationSniff now throws error for AS keyword not being lowercase +- Squiz SwitchDeclarationSniff now throws errors for CASE/DEFAULT/BREAK keywords not being lowercase +- Squiz ArrayDeclarationSniff now handles multi-token array values when checking alignment +- Squiz standard now enforces a space after cast tokens +- Generic MultipleStatementAlignmentSniff no longer gets confused by assignments inside FOR conditions +- Generic MultipleStatementAlignmentSniff no longer gets confused by the use of list() +- Added Generic SpaceAfterCastSniff to ensure there is a single space after a cast token +- Added Generic NoSpaceAfterCastSniff to ensure there is no whitespace after a cast token +- Added PEAR ClassDeclarationSniff to ensure the opening brace of a class is on the line after the keyword +- Added Squiz ScopeClosingBraceSniff to ensure closing braces are aligned correctly +- Added Squiz EvalSniff to discourage the use of eval() +- Added Squiz LowercaseDeclarationSniff to ensure all declaration keywords are lowercase +- Added Squiz LowercaseClassKeywordsSniff to ensure all class declaration keywords are lowercase +- Added Squiz LowercaseFunctionKeywordsSniff to ensure all function declaration keywords are lowercase +- Added Squiz LowercasePHPFunctionsSniff to ensure all calls to inbuilt PHP functions are lowercase +- Added Squiz CastSpacingSniff to ensure cast statements dont contain whitespace +- Errors no longer thrown when checking 0 length files with verbosity on + +### Fixed +- Fixed bug #11105 : getIncludedSniffs() not working anymore + - Thanks to [Blair Robertson][pear-adviva] for the patch +- Fixed bug #11120 : Uninitialized string offset in AbstractParser.php on line 200 + +## 0.6.0 - 2007-05-15 +### Changed +- The number of errors and warnings found is now shown for each file while checking the file if verbosity is enabled +- Now using PHP_EOL instead of hard-coded \n so output looks good on Windows (feature request #10761) + - Thanks to [Carsten Wiedmann][pear-cwiedmann] for the patch. +- phpcs now exits with status 0 (no errors) or 1 (errors found) (feature request #10348) +- Added new -l command line argument to stop recursion into directories (feature request #10979) + +### Fixed +- Fixed variable name error causing incorrect error message in Squiz ValidVariableNameSniff +- Fixed bug #10757 : Error in ControlSignatureSniff +- Fixed bugs #10751, #10777 : Sniffer class paths handled incorrectly in Windows + - Thanks to [Carsten Wiedmann][pear-cwiedmann] for the patch. +- Fixed bug #10961 : Error "Last parameter comment requires a blank newline after it" thrown +- Fixed bug #10983 : phpcs outputs notices when checking invalid PHP +- Fixed bug #10980 : Incorrect warnings for equals sign + +## 0.5.0 - 2007-04-17 +### Changed +- BC BREAK: Coding standards now require a class to be added so PHP_CodeSniffer can get information from them + - Please read the end user docs for info about the new class required for all coding standards + +- Coding standards can now include sniffs from other standards, or whole standards, without writing new sniff files +- PHP_CodeSniffer_File::isReference() now correctly returns for references in function declarations +- PHP_CodeSniffer_File::isReference() now returns false if you don't pass it a T_BITWISE_AND token +- PHP_CodeSniffer_File now stores the absolute path to the file so sniffs can check file locations correctly +- Fixed undefined index error in AbstractVariableSniff for variables inside an interface function definition +- Added MemberVarSpacingSniff to Squiz standard to enforce one-line spacing between member vars +- Add FunctionCommentThrowTagSniff to Squiz standard to check that @throws tags are correct + +### Fixed +- Fixed problems caused by references and type hints in Squiz FunctionDeclarationArgumentSpacingSniff +- Fixed problems with errors not being thrown for some misaligned @param comments in Squiz FunctionCommentSniff +- Fixed badly spaced comma error being thrown for "extends" class in Squiz ClassDeclarationSniff +- Errors no longer thrown for class method names in Generic ForbiddenFunctionsSniff +- Errors no longer thrown for type hints in front of references in Generic UpperCaseConstantNameSniff +- Errors no longer thrown for correctly indented buffered lines in Squiz ScopeIndexSniff +- Errors no longer thrown for user-defined functions named as forbidden functions in Generic ForbiddenFunctionsSniff +- Errors no longer thrown on __autoload functions in PEAR ValidFunctionNameSniff +- Errors now thrown for __autoload methods in PEAR ValidFunctionNameSniff +- Errors now thrown if constructors or destructors have @return tags in Squiz FunctionCommentSniff +- Errors now thrown if @throws tags dont start with a capital and end with a full stop in Squiz FunctionCommentSniff +- Errors now thrown for invalid @var tag values in Squiz VariableCommentSniff +- Errors now thrown for missing doc comment in Squiz VariableCommentSniff +- Errors now thrown for unspaced operators in FOR loop declarations in Squiz OperatorSpacingSniff +- Errors now thrown for using ob_get_clean/flush functions to end buffers in Squiz OutputBufferingIndentSniff +- Errors now thrown for all missing member variable comments in Squiz VariableCommentSniff + +## 0.4.0 - 2007-02-19 +### Changed +- Standard name specified with --standard command line argument is no longer case sensitive +- Long error and warning messages are now wrapped to 80 characters in the full error report (thanks Endre Czirbesz) +- Shortened a lot of error and warning messages so they don't take up so much room +- Squiz FunctionCommentSniff now checks that param comments start with a capital letter and end with a full stop +- Squiz FunctionSpacingSniff now reports incorrect lines below function on closing brace, not function keyword +- Squiz FileCommentSniff now checks that there are no blank lines between the open PHP tag and the comment +- PHP_CodeSniffer_File::isReference() now returns correctly when checking refs on right side of => + +### Fixed +- Fixed incorrect error with switch closing brace in Squiz SwitchDeclarationSniff +- Fixed missing error when multiple statements are not aligned correctly with object operators +- Fixed incorrect errors for some PHP special variables in Squiz ValidVariableNameSniff +- Fixed incorrect errors for arrays that only contain other arrays in Squiz ArrayDeclarationSniff +- Fixed bug #9844 : throw new Exception(\n accidentally reported as error but it ain't + +## 0.3.0 - 2007-01-11 +### Changed +- Updated package.xml to version 2 +- Specifying coding standard on command line is now optional, even if you have multiple standards installed + - PHP_CodeSniffer uses the PEAR coding standard by default if no standard is specified +- New command line option, --extensions, to specify a comma separated list of file extensions to check +- Converted all unit tests to PHPUnit 3 format +- Added new coding standard, Squiz, that can be used as an alternative to PEAR + - also contains more examples of sniffs + - some may be moved into the Generic coding standard if required +- Added MultipleStatementAlignmentSniff to Generic standard +- Added ScopeIndentSniff to Generic standard +- Added ForbiddenFunctionsSniff to Generic standard +- Added FileCommentSniff to PEAR standard +- Added ClassCommentSniff to PEAR standard +- Added FunctionCommentSniff to PEAR standard +- Change MultipleStatementSniff to MultipleStatementAlignmentSniff in PEAR standard +- Replaced Methods directory with Functions directory in Generic and PEAR standards + - also renamed some of the sniffs in those directories +- Updated file, class and method comments for all files + +### Fixed +- Fixed bug #9274 : nested_parenthesis element not set for open and close parenthesis tokens +- Fixed bug #9411 : too few pattern characters cause incorrect error report + +## 0.2.1 - 2006-11-09 +### Fixed +- Fixed bug #9274 : nested_parenthesis element not set for open and close parenthesis tokens + +## 0.2.0 - 2006-10-13 +### Changed +- Added a generic standards package that will contain generic sniffs to be used in specific coding standards + - thanks to Frederic Poeydomenge for the idea +- Changed PEAR standard to use generic sniffs where available +- Added LowerCaseConstantSniff to Generic standard +- Added UpperCaseConstantSniff to Generic standard +- Added DisallowShortOpenTagSniff to Generic standard +- Added LineLengthSniff to Generic standard +- Added UpperCaseConstantNameSniff to Generic standard +- Added OpeningMethodBraceBsdAllmanSniff to Generic standard (contrib by Frederic Poeydomenge) +- Added OpeningMethodBraceKernighanRitchieSniff to Generic standard (contrib by Frederic Poeydomenge) +- Added framework for core PHP_CodeSniffer unit tests +- Added unit test for PHP_CodeSniffer:isCamelCaps method +- ScopeClosingBraceSniff now checks indentation of BREAK statements +- Added new command line arg (-vv) to show developer debug output + +### Fixed +- Fixed some coding standard errors +- Fixed bug #8834 : Massive memory consumption +- Fixed bug #8836 : path case issues in package.xml +- Fixed bug #8843 : confusion on nested switch() +- Fixed bug #8841 : comments taken as whitespace +- Fixed bug #8884 : another problem with nested switch() statements + +## 0.1.1 - 2006-09-25 +### Changed +- Added unit tests for all PEAR sniffs +- Exception class now extends from PEAR_Exception + +### Fixed +- Fixed summary report so files without errors but with warnings are not shown when warnings are hidden + +## 0.1.0 - 2006-09-19 +### Changed +- Reorganised package contents to conform to PEAR standards +- Changed version numbering to conform to PEAR standards +- Removed duplicate require_once() of Exception.php from CodeSniffer.php + +## 0.0.5 - 2006-09-18 +### Fixed +- Fixed .bat file for situation where php.ini cannot be found so include_path is not set + +## 0.0.4 - 2006-08-28 +### Changed +- Added .bat file for easier running of PHP_CodeSniffer on Windows +- Sniff that checks method names now works for PHP4 style code where there is no scope keyword +- Sniff that checks method names now works for PHP4 style constructors +- Sniff that checks method names no longer incorrectly reports error with magic methods +- Sniff that checks method names now reports errors with non-magic methods prefixed with __ +- Sniff that checks for constant names no longer incorrectly reports errors with heredoc strings +- Sniff that checks for constant names no longer incorrectly reports errors with created objects +- Sniff that checks indentation no longer incorrectly reports errors with heredoc strings +- Sniff that checks indentation now correctly reports errors with improperly indented multi-line strings +- Sniff that checks function declarations now checks for spaces before and after an equals sign for default values +- Sniff that checks function declarations no longer incorrectly reports errors with multi-line declarations +- Sniff that checks included code no longer incorrectly reports errors when return value is used conditionally +- Sniff that checks opening brace of function no longer incorrectly reports errors with multi-line declarations +- Sniff that checks spacing after commas in function calls no longer reports too many errors for some code +- Sniff that checks control structure declarations now gives more descriptive error message + +## 0.0.3 - 2006-08-22 +### Changed +- Added sniff to check for invalid class and interface names +- Added sniff to check for invalid function and method names +- Added sniff to warn if line is greater than 85 characters +- Added sniff to check that function calls are in the correct format +- Added command line arg to print current version (--version) + +### Fixed +- Fixed error where comments were not allowed on the same line as a control structure declaration + +## 0.0.2 - 2006-07-25 +### Changed +- Removed the including of checked files to stop errors caused by parsing them +- Removed the use of reflection so checked files do not have to be included +- Memory usage has been greatly reduced +- Much faster tokenising and checking times +- Reworked the PEAR coding standard sniffs (much faster now) +- Fix some bugs with the PEAR scope indentation standard +- Better checking for installed coding standards +- Can now accept multiple files and dirs on the command line +- Added an option to list installed coding standards +- Added an option to print a summary report (number of errors and warnings shown for each file) +- Added an option to hide warnings from reports +- Added an option to print verbose output (so you know what is going on) +- Reordered command line args to put switches first (although order is not enforced) +- Switches can now be specified together (eg. php -nv) as well as separately (phpcs -n -v) + +## 0.0.1 - 2006-07-19 +### Added +- Initial preview release + + + +[Unreleased]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/master...HEAD +[3.8.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.7.2...3.8.0 +[3.7.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.7.1...3.7.2 +[3.7.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.7.0...3.7.1 +[3.7.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.6.2...3.7.0 +[3.6.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.6.1...3.6.2 +[3.6.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.8...3.6.0 +[3.5.8]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.7...3.5.8 +[3.5.7]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.6...3.5.7 +[3.5.6]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.5...3.5.6 +[3.5.5]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.4.2...3.5.0 +[3.4.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.3.2...3.4.0 +[3.3.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.3.1...3.3.2 +[3.3.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.2.3...3.3.0 +[3.2.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.1.1...3.2.0 +[3.1.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.1.0...3.1.1 +[3.1.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0RC4...3.0.0 +[3.0.0RC4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0RC3...3.0.0RC4 +[3.0.0RC3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0RC2...3.0.0RC3 +[3.0.0RC2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0RC1...3.0.0RC2 +[3.0.0RC1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/3.0.0a1...3.0.0RC1 +[3.0.0a1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.9.2...3.0.0a1 +[2.9.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.9.1...2.9.2 +[2.9.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.9.0...2.9.1 +[2.9.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.8.1...2.9.0 +[2.8.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.8.0...2.8.1 +[2.8.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.7.1...2.8.0 +[2.7.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.7.0...2.7.1 +[2.7.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.6.2...2.7.0 +[2.6.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.6.1...2.6.2 +[2.6.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.6.0...2.6.1 +[2.6.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.5.1...2.6.0 +[2.5.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.5.0...2.5.1 +[2.5.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.4.0...2.5.0 +[2.4.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.3.4...2.4.0 +[2.3.4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.3.3...2.3.4 +[2.3.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.3.2...2.3.3 +[2.3.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.3.1...2.3.2 +[2.3.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.3.0...2.3.1 +[2.3.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.2.0...2.3.0 +[2.2.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.1.0...2.2.0 +[2.1.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0...2.1.0 +[2.0.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0RC4...2.0.0 +[2.0.0RC4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0RC3...2.0.0RC4 +[2.0.0RC3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0RC2...2.0.0RC3 +[2.0.0RC2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0RC1...2.0.0RC2 +[2.0.0RC1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0a2...2.0.0RC1 +[2.0.0a2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/2.0.0a1...2.0.0a2 +[2.0.0a1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.6...2.0.0a1 +[1.5.6]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.5...1.5.6 +[1.5.5]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.4...1.5.5 +[1.5.4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.3...1.5.4 +[1.5.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.2...1.5.3 +[1.5.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.0RC4...1.5.0 +[1.5.0RC4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.0RC3...1.5.0RC4 +[1.5.0RC3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.0RC2...1.5.0RC3 +[1.5.0RC2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.5.0RC1...1.5.0RC2 +[1.5.0RC1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.8...1.5.0RC1 +[1.4.8]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.7...1.4.8 +[1.4.7]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.6...1.4.7 +[1.4.6]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.5...1.4.6 +[1.4.5]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.4...1.4.5 +[1.4.4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.3...1.4.4 +[1.4.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.2...1.4.3 +[1.4.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.6...1.4.0 +[1.3.6]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.5...1.3.6 +[1.3.5]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.4...1.3.5 +[1.3.4]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.3...1.3.4 +[1.3.3]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.2...1.3.3 +[1.3.2]: https://github.com/PHPCSStandards/PHP_CodeSniffer/compare/1.3.1...1.3.2 + + + +[@2shediac]: https://github.com/2shediac +[@ablyler]: https://github.com/ablyler +[@aboks]: https://github.com/aboks +[@abulford]: https://github.com/abulford +[@afilina]: https://github.com/afilina +[@aik099]: https://github.com/aik099 +[@akarmazyn]: https://github.com/akarmazyn +[@akkie]: https://github.com/akkie +[@alcohol]: https://github.com/alcohol +[@alekitto]: https://github.com/alekitto +[@AlexHowansky]: https://github.com/AlexHowansky +[@anbuc]: https://github.com/anbuc +[@andrei-propertyguru]: https://github.com/andrei-propertyguru +[@AndrewDawes]: https://github.com/AndrewDawes +[@andygrunwald]: https://github.com/andygrunwald +[@annechko]: https://github.com/annechko +[@anomiex]: https://github.com/anomiex +[@arnested]: https://github.com/arnested +[@asnyder]: https://github.com/asnyder +[@Astinus-Eberhard]: https://github.com/Astinus-Eberhard +[@axlon]: https://github.com/axlon +[@bayleedev]: https://github.com/bayleedev +[@becoded]: https://github.com/becoded +[@Benjamin-Loison]: https://github.com/Benjamin-Loison +[@benmatselby]: https://github.com/benmatselby +[@Billz95]: https://github.com/Billz95 +[@biozshock]: https://github.com/biozshock +[@bkdotcom]: https://github.com/bkdotcom +[@bladeofsteel]: https://github.com/bladeofsteel +[@blerou]: https://github.com/blerou +[@blue32a]: https://github.com/blue32a +[@bondas83]: https://github.com/bondas83 +[@boonkerz]: https://github.com/boonkerz +[@BRMatt]: https://github.com/BRMatt +[@CandySunPlus]: https://github.com/CandySunPlus +[@ceeram]: https://github.com/ceeram +[@cixtor]: https://github.com/cixtor +[@claylo]: https://github.com/claylo +[@codebymikey]: https://github.com/codebymikey +[@covex-nn]: https://github.com/covex-nn +[@cweiske]: https://github.com/cweiske +[@Daimona]: https://github.com/Daimona +[@danez]: https://github.com/danez +[@DannyvdSluijs]: https://github.com/DannyvdSluijs +[@das-peter]: https://github.com/das-peter +[@datengraben]: https://github.com/datengraben +[@david-binda]: https://github.com/david-binda +[@Decave]: https://github.com/Decave +[@dereuromark]: https://github.com/dereuromark +[@derrabus]: https://github.com/derrabus +[@deviantintegral]: https://github.com/deviantintegral +[@dhensby]: https://github.com/dhensby +[@dingo-d]: https://github.com/dingo-d +[@dominics]: https://github.com/dominics +[@donatj]: https://github.com/donatj +[@dryabkov]: https://github.com/dryabkov +[@dschniepp]: https://github.com/dschniepp +[@duncan3dc]: https://github.com/duncan3dc +[@edorian]: https://github.com/edorian +[@elazar]: https://github.com/elazar +[@ElvenSpellmaker]: https://github.com/ElvenSpellmaker +[@emil-nasso]: https://github.com/emil-nasso +[@enl]: https://github.com/enl +[@erikwiffin]: https://github.com/erikwiffin +[@eser]: https://github.com/eser +[@exussum12]: https://github.com/exussum12 +[@fabacino]: https://github.com/fabacino +[@fabre-thibaud]: https://github.com/fabre-thibaud +[@fcool]: https://github.com/fcool +[@filips123]: https://github.com/filips123 +[@Fischer-Bjoern]: https://github.com/Fischer-Bjoern +[@fonsecas72]: https://github.com/fonsecas72 +[@fredden]: https://github.com/fredden +[@GaryJones]: https://github.com/GaryJones +[@ghostal]: https://github.com/ghostal +[@ghunti]: https://github.com/ghunti +[@gmponos]: https://github.com/gmponos +[@gnutix]: https://github.com/gnutix +[@goatherd]: https://github.com/goatherd +[@grongor]: https://github.com/grongor +[@grzr]: https://github.com/grzr +[@gwharton]: https://github.com/gwharton +[@hashar]: https://github.com/hashar +[@helgi]: https://github.com/helgi +[@hernst42]: https://github.com/hernst42 +[@iammattcoleman]: https://github.com/iammattcoleman +[@ihabunek]: https://github.com/ihabunek +[@illusori]: https://github.com/illusori +[@index0h]: https://github.com/index0h +[@ivuorinen]: https://github.com/ivuorinen +[@jasonmccreary]: https://github.com/jasonmccreary +[@javer]: https://github.com/javer +[@JDGrimes]: https://github.com/JDGrimes +[@jedgell]: https://github.com/jedgell +[@jeffslofish]: https://github.com/jeffslofish +[@jmarcil]: https://github.com/jmarcil +[@jnrbsn]: https://github.com/jnrbsn +[@joelposti]: https://github.com/joelposti +[@johanderuijter]: https://github.com/johanderuijter +[@johnmaguire]: https://github.com/johnmaguire +[@johnpbloch]: https://github.com/johnpbloch +[@JorisDebonnet]: https://github.com/JorisDebonnet +[@josephzidell]: https://github.com/josephzidell +[@joshdavis11]: https://github.com/joshdavis11 +[@jpuck]: https://github.com/jpuck +[@jrfnl]: https://github.com/jrfnl +[@kdebisschop]: https://github.com/kdebisschop +[@kenguest]: https://github.com/kenguest +[@klausi]: https://github.com/klausi +[@Konafets]: https://github.com/Konafets +[@kristofser]: https://github.com/kristofser +[@ksimka]: https://github.com/ksimka +[@ktomk]: https://github.com/ktomk +[@kukulich]: https://github.com/kukulich +[@legoktm]: https://github.com/legoktm +[@lmanzke]: https://github.com/lmanzke +[@localheinz]: https://github.com/localheinz +[@lucc]: https://github.com/lucc +[@MacDada]: https://github.com/MacDada +[@Majkl578]: https://github.com/Majkl578 +[@manuelpichler]: https://github.com/manuelpichler +[@marcospassos]: https://github.com/marcospassos +[@MarkBaker]: https://github.com/MarkBaker +[@MarkMaldaba]: https://github.com/MarkMaldaba +[@martinssipenko]: https://github.com/martinssipenko +[@marvasDE]: https://github.com/marvasDE +[@MasterOdin]: https://github.com/MasterOdin +[@mathroc]: https://github.com/mathroc +[@maxgalbu]: https://github.com/maxgalbu +[@mcuelenaere]: https://github.com/mcuelenaere +[@mhujer]: https://github.com/mhujer +[@michaelbutler]: https://github.com/michaelbutler +[@michalbundyra]: https://github.com/michalbundyra +[@Morerice]: https://github.com/Morerice +[@morozov]: https://github.com/morozov +[@mrkrstphr]: https://github.com/mrkrstphr +[@mythril]: https://github.com/mythril +[@Naelyth]: https://github.com/Naelyth +[@ndm2]: https://github.com/ndm2 +[@nicholascus]: https://github.com/nicholascus +[@NickDickinsonWilde]: https://github.com/NickDickinsonWilde +[@nkovacs]: https://github.com/nkovacs +[@nubs]: https://github.com/nubs +[@o5]: https://github.com/o5 +[@ofbeaton]: https://github.com/ofbeaton +[@olemartinorg]: https://github.com/olemartinorg +[@ondrejmirtes]: https://github.com/ondrejmirtes +[@orx0r]: https://github.com/orx0r +[@ostrolucky]: https://github.com/ostrolucky +[@pfrenssen]: https://github.com/pfrenssen +[@phil-davis]: https://github.com/phil-davis +[@photodude]: https://github.com/photodude +[@r3nat]: https://github.com/r3nat +[@raul338]: https://github.com/raul338 +[@realmfoo]: https://github.com/realmfoo +[@renaatdemuynck]: https://github.com/renaatdemuynck +[@renan]: https://github.com/renan +[@rhorber]: https://github.com/rhorber +[@rmccue]: https://github.com/rmccue +[@robocoder]: https://github.com/robocoder +[@rodrigoprimo]: https://github.com/rodrigoprimo +[@rogeriopradoj]: https://github.com/rogeriopradoj +[@rovangju]: https://github.com/rovangju +[@rvanvelzen]: https://github.com/rvanvelzen +[@saltybeagle]: https://github.com/saltybeagle +[@samlev]: https://github.com/samlev +[@scato]: https://github.com/scato +[@schlessera]: https://github.com/schlessera +[@schnittstabil]: https://github.com/schnittstabil +[@sebastianbergmann]: https://github.com/sebastianbergmann +[@sertand]: https://github.com/sertand +[@shanethehat]: https://github.com/shanethehat +[@shivammathur]: https://github.com/shivammathur +[@simonsan]: https://github.com/simonsan +[@sjlangley]: https://github.com/sjlangley +[@sserbin]: https://github.com/sserbin +[@stefanlenselink]: https://github.com/stefanlenselink +[@SteveTalbot]: https://github.com/SteveTalbot +[@storeman]: https://github.com/storeman +[@stronk7]: https://github.com/stronk7 +[@svycka]: https://github.com/svycka +[@syranez]: https://github.com/syranez +[@tasuki]: https://github.com/tasuki +[@tim-bezhashvyly]: https://github.com/tim-bezhashvyly +[@TomHAnderson]: https://github.com/TomHAnderson +[@thewilkybarkid]: https://github.com/thewilkybarkid +[@thiemowmde]: https://github.com/thiemowmde +[@thomasjfox]: https://github.com/thomasjfox +[@till]: https://github.com/till +[@timoschinkel]: https://github.com/timoschinkel +[@uniquexor]: https://github.com/uniquexor +[@valorin]: https://github.com/valorin +[@VasekPurchart]: https://github.com/VasekPurchart +[@VincentLanglet]: https://github.com/VincentLanglet +[@waltertamboer]: https://github.com/waltertamboer +[@westonruter]: https://github.com/westonruter +[@willemstuursma]: https://github.com/willemstuursma +[@wimg]: https://github.com/wimg +[@wvega]: https://github.com/wvega +[@xalopp]: https://github.com/xalopp +[@xjm]: https://github.com/xjm +[@xt99]: https://github.com/xt99 +[@yesmeck]: https://github.com/yesmeck +[@zBart]: https://github.com/zBart +[pear-adviva]: https://pear.php.net/user/adviva +[pear-bakert]: https://pear.php.net/user/bakert +[pear-bjorn]: https://pear.php.net/user/bjorn +[pear-boxgav]: https://pear.php.net/user/boxgav +[pear-burci]: https://pear.php.net/user/burci +[pear-conf]: https://pear.php.net/user/conf +[pear-cwiedmann]: https://pear.php.net/user/cwiedmann +[pear-dollyaswin]: https://pear.php.net/user/dollyaswin +[pear-dvino]: https://pear.php.net/user/dvino +[pear-et3w503]: https://pear.php.net/user/et3w503 +[pear-gemineye]: https://pear.php.net/user/gemineye +[pear-kwinahradsky]: https://pear.php.net/user/kwinahradsky +[pear-ljmaskey]: https://pear.php.net/user/ljmaskey +[pear-mccammos]: https://pear.php.net/user/mccammos +[pear-pete]: https://pear.php.net/user/pete +[pear-recurser]: https://pear.php.net/user/recurser +[pear-renoiv]: https://pear.php.net/user/renoiv +[pear-rquadling]: https://pear.php.net/user/rquadling +[pear-ryba]: https://pear.php.net/user/ryba +[pear-thezero]: https://pear.php.net/user/thezero +[pear-thing2b]: https://pear.php.net/user/thing2b +[pear-tomdesp]: https://pear.php.net/user/tomdesp +[pear-troehr]: https://pear.php.net/user/troehr +[pear-weirdan]: https://pear.php.net/user/weirdan +[pear-wloche]: https://pear.php.net/user/wloche +[pear-woellchen]: https://pear.php.net/user/woellchen +[pear-youngian]: https://pear.php.net/user/youngian + diff --git a/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist b/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist new file mode 100644 index 0000000..f95058f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist @@ -0,0 +1,9 @@ + 'PSR2', + 'report_format' => 'summary', + 'show_warnings' => '0', + 'show_progress' => '1', + 'report_width' => '120', +); +?> diff --git a/vendor/squizlabs/php_codesniffer/README.md b/vendor/squizlabs/php_codesniffer/README.md new file mode 100644 index 0000000..383fed2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/README.md @@ -0,0 +1,147 @@ +PHP_CodeSniffer +===================================================== + + + +> [!NOTE] +> This package is the continuation of the now abandoned [PHP_CodeSniffer package which was created by Squizlabs](https://github.com/squizlabs/PHP_CodeSniffer). + +## About + +PHP_CodeSniffer is a set of two PHP scripts; the main `phpcs` script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second `phpcbf` script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. + + +## Requirements + +PHP_CodeSniffer requires PHP version 5.4.0 or greater, although individual sniffs may have additional requirements such as external applications and scripts. See the [Configuration Options manual page](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Configuration-Options) for a list of these requirements. + +If you're using PHP_CodeSniffer as part of a team, or you're running it on a [CI](https://en.wikipedia.org/wiki/Continuous_integration) server, you may want to configure your project's settings [using a configuration file](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file). + + +## Installation + +The easiest way to get started with PHP_CodeSniffer is to download the Phar files for each of the commands: +```bash +# Download using curl +curl -OL https://phars.phpcodesniffer.com/phpcs.phar +curl -OL https://phars.phpcodesniffer.com/phpcbf.phar + +# Or download using wget +wget https://phars.phpcodesniffer.com/phpcs.phar +wget https://phars.phpcodesniffer.com/phpcbf.phar + +# Then test the downloaded PHARs +php phpcs.phar -h +php phpcbf.phar -h +``` + +These Phars are signed with the official Release key for PHPCS with the +fingerprint `95DE 904A B800 754A 11D8 0B60 5E6D DE99 8AB7 3B8E`. + +### Composer +If you use Composer, you can install PHP_CodeSniffer system-wide with the following command: +```bash +composer global require "squizlabs/php_codesniffer=*" +``` +Make sure you have the composer bin dir in your PATH. The default value is `~/.composer/vendor/bin/`, but you can check the value that you need to use by running `composer global config bin-dir --absolute`. + +Or alternatively, include a dependency for `squizlabs/php_codesniffer` in your `composer.json` file. For example: + +```json +{ + "require-dev": { + "squizlabs/php_codesniffer": "^3.0" + } +} +``` + +You will then be able to run PHP_CodeSniffer from the vendor bin directory: +```bash +./vendor/bin/phpcs -h +./vendor/bin/phpcbf -h +``` +### Phive +If you use Phive, you can install PHP_CodeSniffer as a project tool using the following commands: +```bash +phive install --trust-gpg-keys 95DE904AB800754A11D80B605E6DDE998AB73B8E phpcs +phive install --trust-gpg-keys 95DE904AB800754A11D80B605E6DDE998AB73B8E phpcbf +``` +You will then be able to run PHP_CodeSniffer from the `tools` directory: +```bash +./tools/phpcs -h +./tools/phpcbf -h +``` +### Git Clone +You can also download the PHP_CodeSniffer source and run the `phpcs` and `phpcbf` commands directly from the Git clone: +```bash +git clone https://github.com/PHPCSStandards/PHP_CodeSniffer.git +cd PHP_CodeSniffer +php bin/phpcs -h +php bin/phpcbf -h +``` +## Getting Started + +The default coding standard used by PHP_CodeSniffer is the PEAR coding standard. To check a file against the PEAR coding standard, simply specify the file's location: +```bash +phpcs /path/to/code/myfile.php +``` +Or if you wish to check an entire directory you can specify the directory location instead of a file. +```bash +phpcs /path/to/code-directory +``` +If you wish to check your code against the PSR-12 coding standard, use the `--standard` command line argument: +```bash +phpcs --standard=PSR12 /path/to/code-directory +``` + +If PHP_CodeSniffer finds any coding standard errors, a report will be shown after running the command. + +Full usage information and example reports are available on the [usage page](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Usage). + +## Documentation + +The documentation for PHP_CodeSniffer is available on the [GitHub wiki](https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki). + +## Issues + +Bug reports and feature requests can be submitted on the [GitHub Issue Tracker](https://github.com/PHPCSStandards/PHP_CodeSniffer/issues). + +## Contributing + +See [CONTRIBUTING.md](.github/CONTRIBUTING.md) for information. + +## Versioning + +PHP_CodeSniffer uses a `MAJOR.MINOR.PATCH` version number format. + +The `MAJOR` version is incremented when: +- backwards-incompatible changes are made to how the `phpcs` or `phpcbf` commands are used, or +- backwards-incompatible changes are made to the `ruleset.xml` format, or +- backwards-incompatible changes are made to the API used by sniff developers, or +- custom PHP_CodeSniffer token types are removed, or +- existing sniffs are removed from PHP_CodeSniffer entirely + +The `MINOR` version is incremented when: +- new backwards-compatible features are added to the `phpcs` and `phpcbf` commands, or +- backwards-compatible changes are made to the `ruleset.xml` format, or +- backwards-compatible changes are made to the API used by sniff developers, or +- new sniffs are added to an included standard, or +- existing sniffs are removed from an included standard + +> NOTE: Backwards-compatible changes to the API used by sniff developers will allow an existing sniff to continue running without producing fatal errors but may not result in the sniff reporting the same errors as it did previously without changes being required. + +The `PATCH` version is incremented when: +- backwards-compatible bug fixes are made + +> NOTE: As PHP_CodeSniffer exists to report and fix issues, most bugs are the result of coding standard errors being incorrectly reported or coding standard errors not being reported when they should be. This means that the messages produced by PHP_CodeSniffer, and the fixes it makes, are likely to be different between PATCH versions. diff --git a/vendor/squizlabs/php_codesniffer/autoload.php b/vendor/squizlabs/php_codesniffer/autoload.php new file mode 100644 index 0000000..7e546bb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/autoload.php @@ -0,0 +1,342 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +if (class_exists('PHP_CodeSniffer\Autoload', false) === false) { + class Autoload + { + + /** + * The composer autoloader. + * + * @var \Composer\Autoload\ClassLoader + */ + private static $composerAutoloader = null; + + /** + * A mapping of file names to class names. + * + * @var array + */ + private static $loadedClasses = []; + + /** + * A mapping of class names to file names. + * + * @var array + */ + private static $loadedFiles = []; + + /** + * A list of additional directories to search during autoloading. + * + * This is typically a list of coding standard directories. + * + * @var string[] + */ + private static $searchPaths = []; + + + /** + * Loads a class. + * + * This method only loads classes that exist in the PHP_CodeSniffer namespace. + * All other classes are ignored and loaded by subsequent autoloaders. + * + * @param string $class The name of the class to load. + * + * @return bool + */ + public static function load($class) + { + // Include the composer autoloader if there is one, but re-register it + // so this autoloader runs before the composer one as we need to include + // all files so we can figure out what the class/interface/trait name is. + if (self::$composerAutoloader === null) { + // Make sure we don't try to load any of Composer's classes + // while the autoloader is being setup. + if (strpos($class, 'Composer\\') === 0) { + return; + } + + if (strpos(__DIR__, 'phar://') !== 0 + && @file_exists(__DIR__.'/../../autoload.php') === true + ) { + self::$composerAutoloader = include __DIR__.'/../../autoload.php'; + if (self::$composerAutoloader instanceof \Composer\Autoload\ClassLoader) { + self::$composerAutoloader->unregister(); + self::$composerAutoloader->register(); + } else { + // Something went wrong, so keep going without the autoloader + // although namespaced sniffs might error. + self::$composerAutoloader = false; + } + } else { + self::$composerAutoloader = false; + } + }//end if + + $ds = DIRECTORY_SEPARATOR; + $path = false; + + if (substr($class, 0, 16) === 'PHP_CodeSniffer\\') { + if (substr($class, 0, 22) === 'PHP_CodeSniffer\Tests\\') { + $isInstalled = !is_dir(__DIR__.$ds.'tests'); + if ($isInstalled === false) { + $path = __DIR__.$ds.'tests'; + } else { + $path = '@test_dir@'.$ds.'PHP_CodeSniffer'.$ds.'CodeSniffer'; + } + + $path .= $ds.substr(str_replace('\\', $ds, $class), 22).'.php'; + } else { + $path = __DIR__.$ds.'src'.$ds.substr(str_replace('\\', $ds, $class), 16).'.php'; + } + } + + // See if the composer autoloader knows where the class is. + if ($path === false && self::$composerAutoloader !== false) { + $path = self::$composerAutoloader->findFile($class); + } + + // See if the class is inside one of our alternate search paths. + if ($path === false) { + foreach (self::$searchPaths as $searchPath => $nsPrefix) { + $className = $class; + if ($nsPrefix !== '' && substr($class, 0, strlen($nsPrefix)) === $nsPrefix) { + $className = substr($class, (strlen($nsPrefix) + 1)); + } + + $path = $searchPath.$ds.str_replace('\\', $ds, $className).'.php'; + if (is_file($path) === true) { + break; + } + + $path = false; + } + } + + if ($path !== false && is_file($path) === true) { + self::loadFile($path); + return true; + } + + return false; + + }//end load() + + + /** + * Includes a file and tracks what class or interface was loaded as a result. + * + * @param string $path The path of the file to load. + * + * @return string The fully qualified name of the class in the loaded file. + */ + public static function loadFile($path) + { + if (strpos(__DIR__, 'phar://') !== 0) { + $path = realpath($path); + if ($path === false) { + return false; + } + } + + if (isset(self::$loadedClasses[$path]) === true) { + return self::$loadedClasses[$path]; + } + + $classesBeforeLoad = [ + 'classes' => get_declared_classes(), + 'interfaces' => get_declared_interfaces(), + 'traits' => get_declared_traits(), + ]; + + include $path; + + $classesAfterLoad = [ + 'classes' => get_declared_classes(), + 'interfaces' => get_declared_interfaces(), + 'traits' => get_declared_traits(), + ]; + + $className = self::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + + self::$loadedClasses[$path] = $className; + self::$loadedFiles[$className] = $path; + return self::$loadedClasses[$path]; + + }//end loadFile() + + + /** + * Determine which class was loaded based on the before and after lists of loaded classes. + * + * @param array $classesBeforeLoad The classes/interfaces/traits before the file was included. + * @param array $classesAfterLoad The classes/interfaces/traits after the file was included. + * + * @return string The fully qualified name of the class in the loaded file. + */ + public static function determineLoadedClass($classesBeforeLoad, $classesAfterLoad) + { + $className = null; + + $newClasses = array_diff($classesAfterLoad['classes'], $classesBeforeLoad['classes']); + if (PHP_VERSION_ID < 70400) { + $newClasses = array_reverse($newClasses); + } + + // Since PHP 7.4 get_declared_classes() does not guarantee any order, making + // it impossible to use order to determine which is the parent an which is the child. + // Let's reduce the list of candidates by removing all the classes known to be "parents". + // That way, at the end, only the "main" class just included will remain. + $newClasses = array_reduce( + $newClasses, + function ($remaining, $current) { + return array_diff($remaining, class_parents($current)); + }, + $newClasses + ); + + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === false) { + $className = $name; + break; + } + } + + if ($className === null) { + $newClasses = array_reverse(array_diff($classesAfterLoad['interfaces'], $classesBeforeLoad['interfaces'])); + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === false) { + $className = $name; + break; + } + } + } + + if ($className === null) { + $newClasses = array_reverse(array_diff($classesAfterLoad['traits'], $classesBeforeLoad['traits'])); + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === false) { + $className = $name; + break; + } + } + } + + return $className; + + }//end determineLoadedClass() + + + /** + * Adds a directory to search during autoloading. + * + * @param string $path The path to the directory to search. + * @param string $nsPrefix The namespace prefix used by files under this path. + * + * @return void + */ + public static function addSearchPath($path, $nsPrefix='') + { + self::$searchPaths[$path] = rtrim(trim((string) $nsPrefix), '\\'); + + }//end addSearchPath() + + + /** + * Retrieve the namespaces and paths registered by external standards. + * + * @return array + */ + public static function getSearchPaths() + { + return self::$searchPaths; + + }//end getSearchPaths() + + + /** + * Gets the class name for the given file path. + * + * @param string $path The name of the file. + * + * @throws \Exception If the file path has not been loaded. + * @return string + */ + public static function getLoadedClassName($path) + { + if (isset(self::$loadedClasses[$path]) === false) { + throw new \Exception("Cannot get class name for $path; file has not been included"); + } + + return self::$loadedClasses[$path]; + + }//end getLoadedClassName() + + + /** + * Gets the file path for the given class name. + * + * @param string $class The name of the class. + * + * @throws \Exception If the class name has not been loaded + * @return string + */ + public static function getLoadedFileName($class) + { + if (isset(self::$loadedFiles[$class]) === false) { + throw new \Exception("Cannot get file name for $class; class has not been included"); + } + + return self::$loadedFiles[$class]; + + }//end getLoadedFileName() + + + /** + * Gets the mapping of file names to class names. + * + * @return array + */ + public static function getLoadedClasses() + { + return self::$loadedClasses; + + }//end getLoadedClasses() + + + /** + * Gets the mapping of class names to file names. + * + * @return array + */ + public static function getLoadedFiles() + { + return self::$loadedFiles; + + }//end getLoadedFiles() + + + }//end class + + // Register the autoloader before any existing autoloaders to ensure + // it gets a chance to hear about every autoload request, and record + // the file and class name for it. + spl_autoload_register(__NAMESPACE__.'\Autoload::load', true, true); +}//end if diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcbf b/vendor/squizlabs/php_codesniffer/bin/phpcbf new file mode 100755 index 0000000..2e86a40 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcbf @@ -0,0 +1,19 @@ +#!/usr/bin/env php + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +if (is_file(__DIR__.'/../autoload.php') === true) { + include_once __DIR__.'/../autoload.php'; +} else { + include_once 'PHP/CodeSniffer/autoload.php'; +} + +$runner = new PHP_CodeSniffer\Runner(); +$exitCode = $runner->runPHPCBF(); +exit($exitCode); diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat b/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat new file mode 100644 index 0000000..da3b040 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat @@ -0,0 +1,10 @@ +@echo off +REM PHP Code Beautifier and Fixer fixes violations of a defined coding standard. +REM +REM @author Greg Sherwood +REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) +REM @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + +set PHPBIN=php + +"%PHPBIN%" "%~dp0\phpcbf" %* diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcs b/vendor/squizlabs/php_codesniffer/bin/phpcs new file mode 100755 index 0000000..e8e8b02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcs @@ -0,0 +1,19 @@ +#!/usr/bin/env php + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +if (is_file(__DIR__.'/../autoload.php') === true) { + include_once __DIR__.'/../autoload.php'; +} else { + include_once 'PHP/CodeSniffer/autoload.php'; +} + +$runner = new PHP_CodeSniffer\Runner(); +$exitCode = $runner->runPHPCS(); +exit($exitCode); diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcs.bat b/vendor/squizlabs/php_codesniffer/bin/phpcs.bat new file mode 100755 index 0000000..a95722b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcs.bat @@ -0,0 +1,10 @@ +@echo off +REM PHP_CodeSniffer detects violations of a defined coding standard. +REM +REM @author Greg Sherwood +REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) +REM @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + +set PHPBIN=php + +"%PHPBIN%" "%~dp0\phpcs" %* diff --git a/vendor/squizlabs/php_codesniffer/composer.json b/vendor/squizlabs/php_codesniffer/composer.json new file mode 100644 index 0000000..ae7c760 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/composer.json @@ -0,0 +1,87 @@ +{ + "name": "squizlabs/php_codesniffer", + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "license": "BSD-3-Clause", + "type": "library", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "Former lead" + }, + { + "name": "Juliette Reinders Folmer", + "role": "Current lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" + } + ], + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "support": { + "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", + "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki", + "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy" + }, + "require": { + "php": ">=5.4.0", + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" + }, + "bin": [ + "bin/phpcbf", + "bin/phpcs" + ], + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "scripts": { + "cs": [ + "@php ./bin/phpcs" + ], + "cbf": [ + "@php ./bin/phpcbf" + ], + "test": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/phpunit/phpunit/phpunit tests/AllTests.php --no-coverage" + ], + "coverage": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/phpunit/phpunit/phpunit tests/AllTests.php -d max_execution_time=0" + ], + "coverage-local": [ + "Composer\\Config::disableProcessTimeout", + "@php ./vendor/phpunit/phpunit/phpunit tests/AllTests.php --coverage-html ./build/coverage-html -d max_execution_time=0" + ], + "build": [ + "Composer\\Config::disableProcessTimeout", + "@php -d phar.readonly=0 -f ./scripts/build-phar.php" + ], + "check-all": [ + "@cs", + "@test" + ] + }, + "scripts-descriptions": { + "cs": "Check for code style violations.", + "cbf": "Fix code style violations.", + "test": "Run the unit tests without code coverage.", + "coverage": "Run the unit tests with code coverage.", + "coverage-local": "Run the unit tests with code coverage and generate an HTML report in a 'build' directory.", + "build": "Create PHAR files for PHPCS and PHPCBF.", + "check-all": "Run all checks (phpcs, tests)." + } +} diff --git a/vendor/squizlabs/php_codesniffer/licence.txt b/vendor/squizlabs/php_codesniffer/licence.txt new file mode 100644 index 0000000..9f95b67 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/licence.txt @@ -0,0 +1,24 @@ +Copyright (c) 2012, Squiz Pty Ltd (ABN 77 084 670 600) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 OWNER 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/vendor/squizlabs/php_codesniffer/phpcs.xsd b/vendor/squizlabs/php_codesniffer/phpcs.xsd new file mode 100644 index 0000000..d93dd86 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/phpcs.xsd @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Config.php b/vendor/squizlabs/php_codesniffer/src/Config.php new file mode 100644 index 0000000..d924839 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Config.php @@ -0,0 +1,1745 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Util\Common; + +/** + * Stores the configuration used to run PHPCS and PHPCBF. + * + * @property string[] $files The files and directories to check. + * @property string[] $standards The standards being used for checking. + * @property int $verbosity How verbose the output should be. + * 0: no unnecessary output + * 1: basic output for files being checked + * 2: ruleset and file parsing output + * 3: sniff execution output + * @property bool $interactive Enable interactive checking mode. + * @property int $parallel Check files in parallel. + * @property bool $cache Enable the use of the file cache. + * @property string $cacheFile Path to the file where the cache data should be written + * @property bool $colors Display colours in output. + * @property bool $explain Explain the coding standards. + * @property bool $local Process local files in directories only (no recursion). + * @property bool $showSources Show sniff source codes in report output. + * @property bool $showProgress Show basic progress information while running. + * @property bool $quiet Quiet mode; disables progress and verbose output. + * @property bool $annotations Process phpcs: annotations. + * @property int $tabWidth How many spaces each tab is worth. + * @property string $encoding The encoding of the files being checked. + * @property string[] $sniffs The sniffs that should be used for checking. + * If empty, all sniffs in the supplied standards will be used. + * @property string[] $exclude The sniffs that should be excluded from checking. + * If empty, all sniffs in the supplied standards will be used. + * @property string[] $ignored Regular expressions used to ignore files and folders during checking. + * @property string $reportFile A file where the report output should be written. + * @property string $generator The documentation generator to use. + * @property string $filter The filter to use for the run. + * @property string[] $bootstrap One of more files to include before the run begins. + * @property int|string $reportWidth The maximum number of columns that reports should use for output. + * Set to "auto" for have this value changed to the width of the terminal. + * @property int $errorSeverity The minimum severity an error must have to be displayed. + * @property int $warningSeverity The minimum severity a warning must have to be displayed. + * @property bool $recordErrors Record the content of error messages as well as error counts. + * @property string $suffix A suffix to add to fixed files. + * @property string $basepath A file system location to strip from the paths of files shown in reports. + * @property bool $stdin Read content from STDIN instead of supplied files. + * @property string $stdinContent Content passed directly to PHPCS on STDIN. + * @property string $stdinPath The path to use for content passed on STDIN. + * @property bool $trackTime Whether or not to track sniff run time. + * + * @property array $extensions File extensions that should be checked, and what tokenizer to use. + * E.g., array('inc' => 'PHP'); + * @property array $reports The reports to use for printing output after the run. + * The format of the array is: + * array( + * 'reportName1' => 'outputFile', + * 'reportName2' => null, + * ); + * If the array value is NULL, the report will be written to the screen. + * + * @property string[] $unknown Any arguments gathered on the command line that are unknown to us. + * E.g., using `phpcs -c` will give array('c'); + */ +class Config +{ + + /** + * The current version. + * + * @var string + */ + const VERSION = '3.8.1'; + + /** + * Package stability; either stable, beta or alpha. + * + * @var string + */ + const STABILITY = 'stable'; + + /** + * Default report width when no report width is provided and 'auto' does not yield a valid width. + * + * @var int + */ + const DEFAULT_REPORT_WIDTH = 80; + + /** + * An array of settings that PHPCS and PHPCBF accept. + * + * This array is not meant to be accessed directly. Instead, use the settings + * as if they are class member vars so the __get() and __set() magic methods + * can be used to validate the values. For example, to set the verbosity level to + * level 2, use $this->verbosity = 2; instead of accessing this property directly. + * + * Each of these settings is described in the class comment property list. + * + * @var array + */ + private $settings = [ + 'files' => null, + 'standards' => null, + 'verbosity' => null, + 'interactive' => null, + 'parallel' => null, + 'cache' => null, + 'cacheFile' => null, + 'colors' => null, + 'explain' => null, + 'local' => null, + 'showSources' => null, + 'showProgress' => null, + 'quiet' => null, + 'annotations' => null, + 'tabWidth' => null, + 'encoding' => null, + 'extensions' => null, + 'sniffs' => null, + 'exclude' => null, + 'ignored' => null, + 'reportFile' => null, + 'generator' => null, + 'filter' => null, + 'bootstrap' => null, + 'reports' => null, + 'basepath' => null, + 'reportWidth' => null, + 'errorSeverity' => null, + 'warningSeverity' => null, + 'recordErrors' => null, + 'suffix' => null, + 'stdin' => null, + 'stdinContent' => null, + 'stdinPath' => null, + 'trackTime' => null, + 'unknown' => null, + ]; + + /** + * Whether or not to kill the process when an unknown command line arg is found. + * + * If FALSE, arguments that are not command line options or file/directory paths + * will be ignored and execution will continue. These values will be stored in + * $this->unknown. + * + * @var boolean + */ + public $dieOnUnknownArg; + + /** + * The current command line arguments we are processing. + * + * @var string[] + */ + private $cliArgs = []; + + /** + * Command line values that the user has supplied directly. + * + * @var array> + */ + private static $overriddenDefaults = []; + + /** + * Config file data that has been loaded for the run. + * + * @var array + */ + private static $configData = null; + + /** + * The full path to the config data file that has been loaded. + * + * @var string + */ + private static $configDataFile = null; + + /** + * Automatically discovered executable utility paths. + * + * @var array + */ + private static $executablePaths = []; + + + /** + * Get the value of an inaccessible property. + * + * @param string $name The name of the property. + * + * @return mixed + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid. + */ + public function __get($name) + { + if (array_key_exists($name, $this->settings) === false) { + throw new RuntimeException("ERROR: unable to get value of property \"$name\""); + } + + // Figure out what the terminal width needs to be for "auto". + if ($name === 'reportWidth' && $this->settings[$name] === 'auto') { + if (function_exists('shell_exec') === true) { + $dimensions = shell_exec('stty size 2>&1'); + if (is_string($dimensions) === true && preg_match('|\d+ (\d+)|', $dimensions, $matches) === 1) { + $this->settings[$name] = (int) $matches[1]; + } + } + + if ($this->settings[$name] === 'auto') { + // If shell_exec wasn't available or didn't yield a usable value, set to the default. + // This will prevent subsequent retrievals of the reportWidth from making another call to stty. + $this->settings[$name] = self::DEFAULT_REPORT_WIDTH; + } + } + + return $this->settings[$name]; + + }//end __get() + + + /** + * Set the value of an inaccessible property. + * + * @param string $name The name of the property. + * @param mixed $value The value of the property. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid. + */ + public function __set($name, $value) + { + if (array_key_exists($name, $this->settings) === false) { + throw new RuntimeException("Can't __set() $name; setting doesn't exist"); + } + + switch ($name) { + case 'reportWidth' : + if (is_string($value) === true && $value === 'auto') { + // Nothing to do. Leave at 'auto'. + break; + } + + if (is_int($value) === true) { + $value = abs($value); + } else if (is_string($value) === true && preg_match('`^\d+$`', $value) === 1) { + $value = (int) $value; + } else { + $value = self::DEFAULT_REPORT_WIDTH; + } + break; + + case 'standards' : + $cleaned = []; + + // Check if the standard name is valid, or if the case is invalid. + $installedStandards = Util\Standards::getInstalledStandards(); + foreach ($value as $standard) { + foreach ($installedStandards as $validStandard) { + if (strtolower($standard) === strtolower($validStandard)) { + $standard = $validStandard; + break; + } + } + + $cleaned[] = $standard; + } + + $value = $cleaned; + break; + + // Only track time when explicitly needed. + case 'verbosity': + if ($value > 2) { + $this->settings['trackTime'] = true; + } + break; + case 'reports': + $reports = array_change_key_case($value, CASE_LOWER); + if (array_key_exists('performance', $reports) === true) { + $this->settings['trackTime'] = true; + } + break; + + default : + // No validation required. + break; + }//end switch + + $this->settings[$name] = $value; + + }//end __set() + + + /** + * Check if the value of an inaccessible property is set. + * + * @param string $name The name of the property. + * + * @return bool + */ + public function __isset($name) + { + return isset($this->settings[$name]); + + }//end __isset() + + + /** + * Unset the value of an inaccessible property. + * + * @param string $name The name of the property. + * + * @return void + */ + public function __unset($name) + { + $this->settings[$name] = null; + + }//end __unset() + + + /** + * Get the array of all config settings. + * + * @return array + */ + public function getSettings() + { + return $this->settings; + + }//end getSettings() + + + /** + * Set the array of all config settings. + * + * @param array $settings The array of config settings. + * + * @return void + */ + public function setSettings($settings) + { + return $this->settings = $settings; + + }//end setSettings() + + + /** + * Creates a Config object and populates it with command line values. + * + * @param array $cliArgs An array of values gathered from CLI args. + * @param bool $dieOnUnknownArg Whether or not to kill the process when an + * unknown command line arg is found. + * + * @return void + */ + public function __construct(array $cliArgs=[], $dieOnUnknownArg=true) + { + if (defined('PHP_CODESNIFFER_IN_TESTS') === true) { + // Let everything through during testing so that we can + // make use of PHPUnit command line arguments as well. + $this->dieOnUnknownArg = false; + } else { + $this->dieOnUnknownArg = $dieOnUnknownArg; + } + + if (empty($cliArgs) === true) { + $cliArgs = $_SERVER['argv']; + array_shift($cliArgs); + } + + $this->restoreDefaults(); + $this->setCommandLineValues($cliArgs); + + if (isset(self::$overriddenDefaults['standards']) === false) { + // They did not supply a standard to use. + // Look for a default ruleset in the current directory or higher. + $currentDir = getcwd(); + + $defaultFiles = [ + '.phpcs.xml', + 'phpcs.xml', + '.phpcs.xml.dist', + 'phpcs.xml.dist', + ]; + + do { + foreach ($defaultFiles as $defaultFilename) { + $default = $currentDir.DIRECTORY_SEPARATOR.$defaultFilename; + if (is_file($default) === true) { + $this->standards = [$default]; + break(2); + } + } + + $lastDir = $currentDir; + $currentDir = dirname($currentDir); + } while ($currentDir !== '.' && $currentDir !== $lastDir && Common::isReadable($currentDir) === true); + }//end if + + if (defined('STDIN') === false + || stripos(PHP_OS, 'WIN') === 0 + ) { + return; + } + + $handle = fopen('php://stdin', 'r'); + + // Check for content on STDIN. + if ($this->stdin === true + || (Util\Common::isStdinATTY() === false + && feof($handle) === false) + ) { + $readStreams = [$handle]; + $writeSteams = null; + + $fileContents = ''; + while (is_resource($handle) === true && feof($handle) === false) { + // Set a timeout of 200ms. + if (stream_select($readStreams, $writeSteams, $writeSteams, 0, 200000) === 0) { + break; + } + + $fileContents .= fgets($handle); + } + + if (trim($fileContents) !== '') { + $this->stdin = true; + $this->stdinContent = $fileContents; + self::$overriddenDefaults['stdin'] = true; + self::$overriddenDefaults['stdinContent'] = true; + } + }//end if + + fclose($handle); + + }//end __construct() + + + /** + * Set the command line values. + * + * @param array $args An array of command line arguments to set. + * + * @return void + */ + public function setCommandLineValues($args) + { + $this->cliArgs = $args; + $numArgs = count($args); + + for ($i = 0; $i < $numArgs; $i++) { + $arg = $this->cliArgs[$i]; + if ($arg === '') { + continue; + } + + if ($arg[0] === '-') { + if ($arg === '-') { + // Asking to read from STDIN. + $this->stdin = true; + self::$overriddenDefaults['stdin'] = true; + continue; + } + + if ($arg === '--') { + // Empty argument, ignore it. + continue; + } + + if ($arg[1] === '-') { + $this->processLongArgument(substr($arg, 2), $i); + } else { + $switches = str_split($arg); + foreach ($switches as $switch) { + if ($switch === '-') { + continue; + } + + $this->processShortArgument($switch, $i); + } + } + } else { + $this->processUnknownArgument($arg, $i); + }//end if + }//end for + + }//end setCommandLineValues() + + + /** + * Restore default values for all possible command line arguments. + * + * @return void + */ + public function restoreDefaults() + { + $this->files = []; + $this->standards = ['PEAR']; + $this->verbosity = 0; + $this->interactive = false; + $this->cache = false; + $this->cacheFile = null; + $this->colors = false; + $this->explain = false; + $this->local = false; + $this->showSources = false; + $this->showProgress = false; + $this->quiet = false; + $this->annotations = true; + $this->parallel = 1; + $this->tabWidth = 0; + $this->encoding = 'utf-8'; + $this->extensions = [ + 'php' => 'PHP', + 'inc' => 'PHP', + 'js' => 'JS', + 'css' => 'CSS', + ]; + $this->sniffs = []; + $this->exclude = []; + $this->ignored = []; + $this->reportFile = null; + $this->generator = null; + $this->filter = null; + $this->bootstrap = []; + $this->basepath = null; + $this->reports = ['full' => null]; + $this->reportWidth = 'auto'; + $this->errorSeverity = 5; + $this->warningSeverity = 5; + $this->recordErrors = true; + $this->suffix = ''; + $this->stdin = false; + $this->stdinContent = null; + $this->stdinPath = null; + $this->trackTime = false; + $this->unknown = []; + + $standard = self::getConfigData('default_standard'); + if ($standard !== null) { + $this->standards = explode(',', $standard); + } + + $reportFormat = self::getConfigData('report_format'); + if ($reportFormat !== null) { + $this->reports = [$reportFormat => null]; + } + + $tabWidth = self::getConfigData('tab_width'); + if ($tabWidth !== null) { + $this->tabWidth = (int) $tabWidth; + } + + $encoding = self::getConfigData('encoding'); + if ($encoding !== null) { + $this->encoding = strtolower($encoding); + } + + $severity = self::getConfigData('severity'); + if ($severity !== null) { + $this->errorSeverity = (int) $severity; + $this->warningSeverity = (int) $severity; + } + + $severity = self::getConfigData('error_severity'); + if ($severity !== null) { + $this->errorSeverity = (int) $severity; + } + + $severity = self::getConfigData('warning_severity'); + if ($severity !== null) { + $this->warningSeverity = (int) $severity; + } + + $showWarnings = self::getConfigData('show_warnings'); + if ($showWarnings !== null) { + $showWarnings = (bool) $showWarnings; + if ($showWarnings === false) { + $this->warningSeverity = 0; + } + } + + $reportWidth = self::getConfigData('report_width'); + if ($reportWidth !== null) { + $this->reportWidth = $reportWidth; + } + + $showProgress = self::getConfigData('show_progress'); + if ($showProgress !== null) { + $this->showProgress = (bool) $showProgress; + } + + $quiet = self::getConfigData('quiet'); + if ($quiet !== null) { + $this->quiet = (bool) $quiet; + } + + $colors = self::getConfigData('colors'); + if ($colors !== null) { + $this->colors = (bool) $colors; + } + + if (defined('PHP_CODESNIFFER_IN_TESTS') === false) { + $cache = self::getConfigData('cache'); + if ($cache !== null) { + $this->cache = (bool) $cache; + } + + $parallel = self::getConfigData('parallel'); + if ($parallel !== null) { + $this->parallel = max((int) $parallel, 1); + } + } + + }//end restoreDefaults() + + + /** + * Processes a short (-e) command line argument. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processShortArgument($arg, $pos) + { + switch ($arg) { + case 'h': + case '?': + ob_start(); + $this->printUsage(); + $output = ob_get_contents(); + ob_end_clean(); + throw new DeepExitException($output, 0); + case 'i' : + ob_start(); + Util\Standards::printInstalledStandards(); + $output = ob_get_contents(); + ob_end_clean(); + throw new DeepExitException($output, 0); + case 'v' : + if ($this->quiet === true) { + // Ignore when quiet mode is enabled. + break; + } + + $this->verbosity++; + self::$overriddenDefaults['verbosity'] = true; + break; + case 'l' : + $this->local = true; + self::$overriddenDefaults['local'] = true; + break; + case 's' : + $this->showSources = true; + self::$overriddenDefaults['showSources'] = true; + break; + case 'a' : + $this->interactive = true; + self::$overriddenDefaults['interactive'] = true; + break; + case 'e': + $this->explain = true; + self::$overriddenDefaults['explain'] = true; + break; + case 'p' : + if ($this->quiet === true) { + // Ignore when quiet mode is enabled. + break; + } + + $this->showProgress = true; + self::$overriddenDefaults['showProgress'] = true; + break; + case 'q' : + // Quiet mode disables a few other settings as well. + $this->quiet = true; + $this->showProgress = false; + $this->verbosity = 0; + + self::$overriddenDefaults['quiet'] = true; + break; + case 'm' : + $this->recordErrors = false; + self::$overriddenDefaults['recordErrors'] = true; + break; + case 'd' : + $ini = explode('=', $this->cliArgs[($pos + 1)]); + $this->cliArgs[($pos + 1)] = ''; + if (isset($ini[1]) === true) { + ini_set($ini[0], $ini[1]); + } else { + ini_set($ini[0], true); + } + break; + case 'n' : + if (isset(self::$overriddenDefaults['warningSeverity']) === false) { + $this->warningSeverity = 0; + self::$overriddenDefaults['warningSeverity'] = true; + } + break; + case 'w' : + if (isset(self::$overriddenDefaults['warningSeverity']) === false) { + $this->warningSeverity = $this->errorSeverity; + self::$overriddenDefaults['warningSeverity'] = true; + } + break; + default: + if ($this->dieOnUnknownArg === false) { + $unknown = $this->unknown; + $unknown[] = $arg; + $this->unknown = $unknown; + } else { + $this->processUnknownArgument('-'.$arg, $pos); + } + }//end switch + + }//end processShortArgument() + + + /** + * Processes a long (--example) command-line argument. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processLongArgument($arg, $pos) + { + switch ($arg) { + case 'help': + ob_start(); + $this->printUsage(); + $output = ob_get_contents(); + ob_end_clean(); + throw new DeepExitException($output, 0); + case 'version': + $output = 'PHP_CodeSniffer version '.self::VERSION.' ('.self::STABILITY.') '; + $output .= 'by Squiz and PHPCSStandards'.PHP_EOL; + throw new DeepExitException($output, 0); + case 'colors': + if (isset(self::$overriddenDefaults['colors']) === true) { + break; + } + + $this->colors = true; + self::$overriddenDefaults['colors'] = true; + break; + case 'no-colors': + if (isset(self::$overriddenDefaults['colors']) === true) { + break; + } + + $this->colors = false; + self::$overriddenDefaults['colors'] = true; + break; + case 'cache': + if (isset(self::$overriddenDefaults['cache']) === true) { + break; + } + + if (defined('PHP_CODESNIFFER_IN_TESTS') === false) { + $this->cache = true; + self::$overriddenDefaults['cache'] = true; + } + break; + case 'no-cache': + if (isset(self::$overriddenDefaults['cache']) === true) { + break; + } + + $this->cache = false; + self::$overriddenDefaults['cache'] = true; + break; + case 'ignore-annotations': + if (isset(self::$overriddenDefaults['annotations']) === true) { + break; + } + + $this->annotations = false; + self::$overriddenDefaults['annotations'] = true; + break; + case 'config-set': + if (isset($this->cliArgs[($pos + 1)]) === false + || isset($this->cliArgs[($pos + 2)]) === false + ) { + $error = 'ERROR: Setting a config option requires a name and value'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $key = $this->cliArgs[($pos + 1)]; + $value = $this->cliArgs[($pos + 2)]; + $current = self::getConfigData($key); + + try { + $this->setConfigData($key, $value); + } catch (\Exception $e) { + throw new DeepExitException($e->getMessage().PHP_EOL, 3); + } + + $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL; + + if ($current === null) { + $output .= "Config value \"$key\" added successfully".PHP_EOL; + } else { + $output .= "Config value \"$key\" updated successfully; old value was \"$current\"".PHP_EOL; + } + throw new DeepExitException($output, 0); + case 'config-delete': + if (isset($this->cliArgs[($pos + 1)]) === false) { + $error = 'ERROR: Deleting a config option requires the name of the option'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL; + + $key = $this->cliArgs[($pos + 1)]; + $current = self::getConfigData($key); + if ($current === null) { + $output .= "Config value \"$key\" has not been set".PHP_EOL; + } else { + try { + $this->setConfigData($key, null); + } catch (\Exception $e) { + throw new DeepExitException($e->getMessage().PHP_EOL, 3); + } + + $output .= "Config value \"$key\" removed successfully; old value was \"$current\"".PHP_EOL; + } + throw new DeepExitException($output, 0); + case 'config-show': + ob_start(); + $data = self::getAllConfigData(); + echo 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL; + $this->printConfigData($data); + $output = ob_get_contents(); + ob_end_clean(); + throw new DeepExitException($output, 0); + case 'runtime-set': + if (isset($this->cliArgs[($pos + 1)]) === false + || isset($this->cliArgs[($pos + 2)]) === false + ) { + $error = 'ERROR: Setting a runtime config option requires a name and value'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $key = $this->cliArgs[($pos + 1)]; + $value = $this->cliArgs[($pos + 2)]; + $this->cliArgs[($pos + 1)] = ''; + $this->cliArgs[($pos + 2)] = ''; + self::setConfigData($key, $value, true); + if (isset(self::$overriddenDefaults['runtime-set']) === false) { + self::$overriddenDefaults['runtime-set'] = []; + } + + self::$overriddenDefaults['runtime-set'][$key] = true; + break; + default: + if (substr($arg, 0, 7) === 'sniffs=') { + if (isset(self::$overriddenDefaults['sniffs']) === true) { + break; + } + + $sniffs = explode(',', substr($arg, 7)); + foreach ($sniffs as $sniff) { + if (substr_count($sniff, '.') !== 2) { + $error = 'ERROR: The specified sniff code "'.$sniff.'" is invalid'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + } + + $this->sniffs = $sniffs; + self::$overriddenDefaults['sniffs'] = true; + } else if (substr($arg, 0, 8) === 'exclude=') { + if (isset(self::$overriddenDefaults['exclude']) === true) { + break; + } + + $sniffs = explode(',', substr($arg, 8)); + foreach ($sniffs as $sniff) { + if (substr_count($sniff, '.') !== 2) { + $error = 'ERROR: The specified sniff code "'.$sniff.'" is invalid'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + } + + $this->exclude = $sniffs; + self::$overriddenDefaults['exclude'] = true; + } else if (defined('PHP_CODESNIFFER_IN_TESTS') === false + && substr($arg, 0, 6) === 'cache=' + ) { + if ((isset(self::$overriddenDefaults['cache']) === true + && $this->cache === false) + || isset(self::$overriddenDefaults['cacheFile']) === true + ) { + break; + } + + // Turn caching on. + $this->cache = true; + self::$overriddenDefaults['cache'] = true; + + $this->cacheFile = Util\Common::realpath(substr($arg, 6)); + + // It may not exist and return false instead. + if ($this->cacheFile === false) { + $this->cacheFile = substr($arg, 6); + + $dir = dirname($this->cacheFile); + if (is_dir($dir) === false) { + $error = 'ERROR: The specified cache file path "'.$this->cacheFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + if ($dir === '.') { + // Passed cache file is a file in the current directory. + $this->cacheFile = getcwd().'/'.basename($this->cacheFile); + } else { + if ($dir[0] === '/') { + // An absolute path. + $dir = Util\Common::realpath($dir); + } else { + $dir = Util\Common::realpath(getcwd().'/'.$dir); + } + + if ($dir !== false) { + // Cache file path is relative. + $this->cacheFile = $dir.'/'.basename($this->cacheFile); + } + } + }//end if + + self::$overriddenDefaults['cacheFile'] = true; + + if (is_dir($this->cacheFile) === true) { + $error = 'ERROR: The specified cache file path "'.$this->cacheFile.'" is a directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + } else if (substr($arg, 0, 10) === 'bootstrap=') { + $files = explode(',', substr($arg, 10)); + $bootstrap = []; + foreach ($files as $file) { + $path = Util\Common::realpath($file); + if ($path === false) { + $error = 'ERROR: The specified bootstrap file "'.$file.'" does not exist'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $bootstrap[] = $path; + } + + $this->bootstrap = array_merge($this->bootstrap, $bootstrap); + self::$overriddenDefaults['bootstrap'] = true; + } else if (substr($arg, 0, 10) === 'file-list=') { + $fileList = substr($arg, 10); + $path = Util\Common::realpath($fileList); + if ($path === false) { + $error = 'ERROR: The specified file list "'.$fileList.'" does not exist'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $files = file($path); + foreach ($files as $inputFile) { + $inputFile = trim($inputFile); + + // Skip empty lines. + if ($inputFile === '') { + continue; + } + + $this->processFilePath($inputFile); + } + } else if (substr($arg, 0, 11) === 'stdin-path=') { + if (isset(self::$overriddenDefaults['stdinPath']) === true) { + break; + } + + $this->stdinPath = Util\Common::realpath(substr($arg, 11)); + + // It may not exist and return false instead, so use whatever they gave us. + if ($this->stdinPath === false) { + $this->stdinPath = trim(substr($arg, 11)); + } + + self::$overriddenDefaults['stdinPath'] = true; + } else if (PHP_CODESNIFFER_CBF === false && substr($arg, 0, 12) === 'report-file=') { + if (isset(self::$overriddenDefaults['reportFile']) === true) { + break; + } + + $this->reportFile = Util\Common::realpath(substr($arg, 12)); + + // It may not exist and return false instead. + if ($this->reportFile === false) { + $this->reportFile = substr($arg, 12); + + $dir = Util\Common::realpath(dirname($this->reportFile)); + if (is_dir($dir) === false) { + $error = 'ERROR: The specified report file path "'.$this->reportFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $this->reportFile = $dir.'/'.basename($this->reportFile); + }//end if + + self::$overriddenDefaults['reportFile'] = true; + + if (is_dir($this->reportFile) === true) { + $error = 'ERROR: The specified report file path "'.$this->reportFile.'" is a directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + } else if (substr($arg, 0, 13) === 'report-width=') { + if (isset(self::$overriddenDefaults['reportWidth']) === true) { + break; + } + + $this->reportWidth = substr($arg, 13); + self::$overriddenDefaults['reportWidth'] = true; + } else if (substr($arg, 0, 9) === 'basepath=') { + if (isset(self::$overriddenDefaults['basepath']) === true) { + break; + } + + self::$overriddenDefaults['basepath'] = true; + + if (substr($arg, 9) === '') { + $this->basepath = null; + break; + } + + $this->basepath = Util\Common::realpath(substr($arg, 9)); + + // It may not exist and return false instead. + if ($this->basepath === false) { + $this->basepath = substr($arg, 9); + } + + if (is_dir($this->basepath) === false) { + $error = 'ERROR: The specified basepath "'.$this->basepath.'" points to a non-existent directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + } else if ((substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-')) { + $reports = []; + + if ($arg[6] === '-') { + // This is a report with file output. + $split = strpos($arg, '='); + if ($split === false) { + $report = substr($arg, 7); + $output = null; + } else { + $report = substr($arg, 7, ($split - 7)); + $output = substr($arg, ($split + 1)); + if ($output === false) { + $output = null; + } else { + $dir = Util\Common::realpath(dirname($output)); + if (is_dir($dir) === false) { + $error = 'ERROR: The specified '.$report.' report file path "'.$output.'" points to a non-existent directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $output = $dir.'/'.basename($output); + + if (is_dir($output) === true) { + $error = 'ERROR: The specified '.$report.' report file path "'.$output.'" is a directory'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + }//end if + }//end if + + $reports[$report] = $output; + } else { + // This is a single report. + if (isset(self::$overriddenDefaults['reports']) === true) { + break; + } + + $reportNames = explode(',', substr($arg, 7)); + foreach ($reportNames as $report) { + $reports[$report] = null; + } + }//end if + + // Remove the default value so the CLI value overrides it. + if (isset(self::$overriddenDefaults['reports']) === false) { + $this->reports = $reports; + } else { + $this->reports = array_merge($this->reports, $reports); + } + + self::$overriddenDefaults['reports'] = true; + } else if (substr($arg, 0, 7) === 'filter=') { + if (isset(self::$overriddenDefaults['filter']) === true) { + break; + } + + $this->filter = substr($arg, 7); + self::$overriddenDefaults['filter'] = true; + } else if (substr($arg, 0, 9) === 'standard=') { + $standards = trim(substr($arg, 9)); + if ($standards !== '') { + $this->standards = explode(',', $standards); + } + + self::$overriddenDefaults['standards'] = true; + } else if (substr($arg, 0, 11) === 'extensions=') { + if (isset(self::$overriddenDefaults['extensions']) === true) { + break; + } + + $extensions = explode(',', substr($arg, 11)); + $newExtensions = []; + foreach ($extensions as $ext) { + $slash = strpos($ext, '/'); + if ($slash !== false) { + // They specified the tokenizer too. + list($ext, $tokenizer) = explode('/', $ext); + $newExtensions[$ext] = strtoupper($tokenizer); + continue; + } + + if (isset($this->extensions[$ext]) === true) { + $newExtensions[$ext] = $this->extensions[$ext]; + } else { + $newExtensions[$ext] = 'PHP'; + } + } + + $this->extensions = $newExtensions; + self::$overriddenDefaults['extensions'] = true; + } else if (substr($arg, 0, 7) === 'suffix=') { + if (isset(self::$overriddenDefaults['suffix']) === true) { + break; + } + + $this->suffix = substr($arg, 7); + self::$overriddenDefaults['suffix'] = true; + } else if (substr($arg, 0, 9) === 'parallel=') { + if (isset(self::$overriddenDefaults['parallel']) === true) { + break; + } + + $this->parallel = max((int) substr($arg, 9), 1); + self::$overriddenDefaults['parallel'] = true; + } else if (substr($arg, 0, 9) === 'severity=') { + $this->errorSeverity = (int) substr($arg, 9); + $this->warningSeverity = $this->errorSeverity; + if (isset(self::$overriddenDefaults['errorSeverity']) === false) { + self::$overriddenDefaults['errorSeverity'] = true; + } + + if (isset(self::$overriddenDefaults['warningSeverity']) === false) { + self::$overriddenDefaults['warningSeverity'] = true; + } + } else if (substr($arg, 0, 15) === 'error-severity=') { + if (isset(self::$overriddenDefaults['errorSeverity']) === true) { + break; + } + + $this->errorSeverity = (int) substr($arg, 15); + self::$overriddenDefaults['errorSeverity'] = true; + } else if (substr($arg, 0, 17) === 'warning-severity=') { + if (isset(self::$overriddenDefaults['warningSeverity']) === true) { + break; + } + + $this->warningSeverity = (int) substr($arg, 17); + self::$overriddenDefaults['warningSeverity'] = true; + } else if (substr($arg, 0, 7) === 'ignore=') { + if (isset(self::$overriddenDefaults['ignored']) === true) { + break; + } + + // Split the ignore string on commas, unless the comma is escaped + // using 1 or 3 slashes (\, or \\\,). + $patterns = preg_split( + '/(?<=(?ignored = $ignored; + self::$overriddenDefaults['ignored'] = true; + } else if (substr($arg, 0, 10) === 'generator=' + && PHP_CODESNIFFER_CBF === false + ) { + if (isset(self::$overriddenDefaults['generator']) === true) { + break; + } + + $this->generator = substr($arg, 10); + self::$overriddenDefaults['generator'] = true; + } else if (substr($arg, 0, 9) === 'encoding=') { + if (isset(self::$overriddenDefaults['encoding']) === true) { + break; + } + + $this->encoding = strtolower(substr($arg, 9)); + self::$overriddenDefaults['encoding'] = true; + } else if (substr($arg, 0, 10) === 'tab-width=') { + if (isset(self::$overriddenDefaults['tabWidth']) === true) { + break; + } + + $this->tabWidth = (int) substr($arg, 10); + self::$overriddenDefaults['tabWidth'] = true; + } else { + if ($this->dieOnUnknownArg === false) { + $eqPos = strpos($arg, '='); + try { + $unknown = $this->unknown; + + if ($eqPos === false) { + $unknown[$arg] = $arg; + } else { + $value = substr($arg, ($eqPos + 1)); + $arg = substr($arg, 0, $eqPos); + $unknown[$arg] = $value; + } + + $this->unknown = $unknown; + } catch (RuntimeException $e) { + // Value is not valid, so just ignore it. + } + } else { + $this->processUnknownArgument('--'.$arg, $pos); + } + }//end if + break; + }//end switch + + }//end processLongArgument() + + + /** + * Processes an unknown command line argument. + * + * Assumes all unknown arguments are files and folders to check. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processUnknownArgument($arg, $pos) + { + // We don't know about any additional switches; just files. + if ($arg[0] === '-') { + if ($this->dieOnUnknownArg === false) { + return; + } + + $error = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + $this->processFilePath($arg); + + }//end processUnknownArgument() + + + /** + * Processes a file path and add it to the file list. + * + * @param string $path The path to the file to add. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processFilePath($path) + { + // If we are processing STDIN, don't record any files to check. + if ($this->stdin === true) { + return; + } + + $file = Util\Common::realpath($path); + if (file_exists($file) === false) { + if ($this->dieOnUnknownArg === false) { + return; + } + + $error = 'ERROR: The file "'.$path.'" does not exist.'.PHP_EOL.PHP_EOL; + $error .= $this->printShortUsage(true); + throw new DeepExitException($error, 3); + } else { + // Can't modify the files array directly because it's not a real + // class member, so need to use this little get/modify/set trick. + $files = $this->files; + $files[] = $file; + $this->files = $files; + self::$overriddenDefaults['files'] = true; + } + + }//end processFilePath() + + + /** + * Prints out the usage information for this script. + * + * @return void + */ + public function printUsage() + { + echo PHP_EOL; + + if (PHP_CODESNIFFER_CBF === true) { + $this->printPHPCBFUsage(); + } else { + $this->printPHPCSUsage(); + } + + echo PHP_EOL; + + }//end printUsage() + + + /** + * Prints out the short usage information for this script. + * + * @param bool $return If TRUE, the usage string is returned + * instead of output to screen. + * + * @return string|void + */ + public function printShortUsage($return=false) + { + if (PHP_CODESNIFFER_CBF === true) { + $usage = 'Run "phpcbf --help" for usage information'; + } else { + $usage = 'Run "phpcs --help" for usage information'; + } + + $usage .= PHP_EOL.PHP_EOL; + + if ($return === true) { + return $usage; + } + + echo $usage; + + }//end printShortUsage() + + + /** + * Prints out the usage information for PHPCS. + * + * @return void + */ + public function printPHPCSUsage() + { + echo 'Usage: phpcs [-nwlsaepqvi] [-d key[=value]] [--colors] [--no-colors]'.PHP_EOL; + echo ' [--cache[=]] [--no-cache] [--tab-width=]'.PHP_EOL; + echo ' [--report=] [--report-file=] [--report-=]'.PHP_EOL; + echo ' [--report-width=] [--basepath=] [--bootstrap=]'.PHP_EOL; + echo ' [--severity=] [--error-severity=] [--warning-severity=]'.PHP_EOL; + echo ' [--runtime-set key value] [--config-set key value] [--config-delete key] [--config-show]'.PHP_EOL; + echo ' [--standard=] [--sniffs=] [--exclude=]'.PHP_EOL; + echo ' [--encoding=] [--parallel=] [--generator=]'.PHP_EOL; + echo ' [--extensions=] [--ignore=] [--ignore-annotations]'.PHP_EOL; + echo ' [--stdin-path=] [--file-list=] [--filter=] - ...'.PHP_EOL; + echo PHP_EOL; + echo ' - Check STDIN instead of local files and directories'.PHP_EOL; + echo ' -n Do not print warnings (shortcut for --warning-severity=0)'.PHP_EOL; + echo ' -w Print both warnings and errors (this is the default)'.PHP_EOL; + echo ' -l Local directory only, no recursion'.PHP_EOL; + echo ' -s Show sniff codes in all reports'.PHP_EOL; + echo ' -a Run interactively'.PHP_EOL; + echo ' -e Explain a standard by showing the sniffs it includes'.PHP_EOL; + echo ' -p Show progress of the run'.PHP_EOL; + echo ' -q Quiet mode; disables progress and verbose output'.PHP_EOL; + echo ' -m Stop error messages from being recorded'.PHP_EOL; + echo ' (saves a lot of memory, but stops many reports from being used)'.PHP_EOL; + echo ' -v Print processed files'.PHP_EOL; + echo ' -vv Print ruleset and token output'.PHP_EOL; + echo ' -vvv Print sniff processing information'.PHP_EOL; + echo ' -i Show a list of installed coding standards'.PHP_EOL; + echo ' -d Set the [key] php.ini value to [value] or [true] if value is omitted'.PHP_EOL; + echo PHP_EOL; + echo ' --help Print this help message'.PHP_EOL; + echo ' --version Print version information'.PHP_EOL; + echo ' --colors Use colors in output'.PHP_EOL; + echo ' --no-colors Do not use colors in output (this is the default)'.PHP_EOL; + echo ' --cache Cache results between runs'.PHP_EOL; + echo ' --no-cache Do not cache results between runs (this is the default)'.PHP_EOL; + echo ' --ignore-annotations Ignore all phpcs: annotations in code comments'.PHP_EOL; + echo PHP_EOL; + echo ' Use a specific file for caching (uses a temporary file by default)'.PHP_EOL; + echo ' A path to strip from the front of file paths inside reports'.PHP_EOL; + echo ' A comma separated list of files to run before processing begins'.PHP_EOL; + echo ' The encoding of the files being checked (default is utf-8)'.PHP_EOL; + echo ' A comma separated list of file extensions to check'.PHP_EOL; + echo ' The type of the file can be specified using: ext/type'.PHP_EOL; + echo ' e.g., module/php,es/js'.PHP_EOL; + echo ' One or more files and/or directories to check'.PHP_EOL; + echo ' A file containing a list of files and/or directories to check (one per line)'.PHP_EOL; + echo ' Use either the "GitModified" or "GitStaged" filter,'.PHP_EOL; + echo ' or specify the path to a custom filter class'.PHP_EOL; + echo ' Use either the "HTML", "Markdown" or "Text" generator'.PHP_EOL; + echo ' (forces documentation generation instead of checking)'.PHP_EOL; + echo ' A comma separated list of patterns to ignore files and directories'.PHP_EOL; + echo ' How many files should be checked simultaneously (default is 1)'.PHP_EOL; + echo ' Print either the "full", "xml", "checkstyle", "csv"'.PHP_EOL; + echo ' "json", "junit", "emacs", "source", "summary", "diff"'.PHP_EOL; + echo ' "svnblame", "gitblame", "hgblame", "notifysend" or "performance",'.PHP_EOL; + echo ' report or specify the path to a custom report class'.PHP_EOL; + echo ' (the "full" report is printed by default)'.PHP_EOL; + echo ' Write the report to the specified file path'.PHP_EOL; + echo ' How many columns wide screen reports should be printed'.PHP_EOL; + echo ' or set to "auto" to use current screen width, where supported'.PHP_EOL; + echo ' The minimum severity required to display an error or warning'.PHP_EOL; + echo ' A comma separated list of sniff codes to include or exclude from checking'.PHP_EOL; + echo ' (all sniffs must be part of the specified standard)'.PHP_EOL; + echo ' The name or path of the coding standard to use'.PHP_EOL; + echo ' If processing STDIN, the file path that STDIN will be processed as'.PHP_EOL; + echo ' The number of spaces each tab represents'.PHP_EOL; + + }//end printPHPCSUsage() + + + /** + * Prints out the usage information for PHPCBF. + * + * @return void + */ + public function printPHPCBFUsage() + { + echo 'Usage: phpcbf [-nwli] [-d key[=value]] [--ignore-annotations] [--bootstrap=]'.PHP_EOL; + echo ' [--standard=] [--sniffs=] [--exclude=] [--suffix=]'.PHP_EOL; + echo ' [--severity=] [--error-severity=] [--warning-severity=]'.PHP_EOL; + echo ' [--tab-width=] [--encoding=] [--parallel=]'.PHP_EOL; + echo ' [--basepath=] [--extensions=] [--ignore=]'.PHP_EOL; + echo ' [--stdin-path=] [--file-list=] [--filter=] - ...'.PHP_EOL; + echo PHP_EOL; + echo ' - Fix STDIN instead of local files and directories'.PHP_EOL; + echo ' -n Do not fix warnings (shortcut for --warning-severity=0)'.PHP_EOL; + echo ' -w Fix both warnings and errors (on by default)'.PHP_EOL; + echo ' -l Local directory only, no recursion'.PHP_EOL; + echo ' -p Show progress of the run'.PHP_EOL; + echo ' -q Quiet mode; disables progress and verbose output'.PHP_EOL; + echo ' -v Print processed files'.PHP_EOL; + echo ' -vv Print ruleset and token output'.PHP_EOL; + echo ' -vvv Print sniff processing information'.PHP_EOL; + echo ' -i Show a list of installed coding standards'.PHP_EOL; + echo ' -d Set the [key] php.ini value to [value] or [true] if value is omitted'.PHP_EOL; + echo PHP_EOL; + echo ' --help Print this help message'.PHP_EOL; + echo ' --version Print version information'.PHP_EOL; + echo ' --ignore-annotations Ignore all phpcs: annotations in code comments'.PHP_EOL; + echo PHP_EOL; + echo ' A path to strip from the front of file paths inside reports'.PHP_EOL; + echo ' A comma separated list of files to run before processing begins'.PHP_EOL; + echo ' The encoding of the files being fixed (default is utf-8)'.PHP_EOL; + echo ' A comma separated list of file extensions to fix'.PHP_EOL; + echo ' The type of the file can be specified using: ext/type'.PHP_EOL; + echo ' e.g., module/php,es/js'.PHP_EOL; + echo ' One or more files and/or directories to fix'.PHP_EOL; + echo ' A file containing a list of files and/or directories to fix (one per line)'.PHP_EOL; + echo ' Use either the "GitModified" or "GitStaged" filter,'.PHP_EOL; + echo ' or specify the path to a custom filter class'.PHP_EOL; + echo ' A comma separated list of patterns to ignore files and directories'.PHP_EOL; + echo ' How many files should be fixed simultaneously (default is 1)'.PHP_EOL; + echo ' The minimum severity required to fix an error or warning'.PHP_EOL; + echo ' A comma separated list of sniff codes to include or exclude from fixing'.PHP_EOL; + echo ' (all sniffs must be part of the specified standard)'.PHP_EOL; + echo ' The name or path of the coding standard to use'.PHP_EOL; + echo ' If processing STDIN, the file path that STDIN will be processed as'.PHP_EOL; + echo ' Write modified files to a filename using this suffix'.PHP_EOL; + echo ' ("diff" and "patch" are not used in this mode)'.PHP_EOL; + echo ' The number of spaces each tab represents'.PHP_EOL; + + }//end printPHPCBFUsage() + + + /** + * Get a single config value. + * + * @param string $key The name of the config value. + * + * @return string|null + * @see setConfigData() + * @see getAllConfigData() + */ + public static function getConfigData($key) + { + $phpCodeSnifferConfig = self::getAllConfigData(); + + if ($phpCodeSnifferConfig === null) { + return null; + } + + if (isset($phpCodeSnifferConfig[$key]) === false) { + return null; + } + + return $phpCodeSnifferConfig[$key]; + + }//end getConfigData() + + + /** + * Get the path to an executable utility. + * + * @param string $name The name of the executable utility. + * + * @return string|null + * @see getConfigData() + */ + public static function getExecutablePath($name) + { + $data = self::getConfigData($name.'_path'); + if ($data !== null) { + return $data; + } + + if ($name === "php") { + // For php, we know the executable path. There's no need to look it up. + return PHP_BINARY; + } + + if (array_key_exists($name, self::$executablePaths) === true) { + return self::$executablePaths[$name]; + } + + if (stripos(PHP_OS, 'WIN') === 0) { + $cmd = 'where '.escapeshellarg($name).' 2> nul'; + } else { + $cmd = 'which '.escapeshellarg($name).' 2> /dev/null'; + } + + $result = exec($cmd, $output, $retVal); + if ($retVal !== 0) { + $result = null; + } + + self::$executablePaths[$name] = $result; + return $result; + + }//end getExecutablePath() + + + /** + * Set a single config value. + * + * @param string $key The name of the config value. + * @param string|null $value The value to set. If null, the config + * entry is deleted, reverting it to the + * default value. + * @param boolean $temp Set this config data temporarily for this + * script run. This will not write the config + * data to the config file. + * + * @return bool + * @see getConfigData() + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written. + */ + public static function setConfigData($key, $value, $temp=false) + { + if (isset(self::$overriddenDefaults['runtime-set']) === true + && isset(self::$overriddenDefaults['runtime-set'][$key]) === true + ) { + return false; + } + + if ($temp === false) { + $path = ''; + if (is_callable('\Phar::running') === true) { + $path = \Phar::running(false); + } + + if ($path !== '') { + $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf'; + } else { + $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf'; + } + + if (is_file($configFile) === true + && is_writable($configFile) === false + ) { + $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + }//end if + + $phpCodeSnifferConfig = self::getAllConfigData(); + + if ($value === null) { + if (isset($phpCodeSnifferConfig[$key]) === true) { + unset($phpCodeSnifferConfig[$key]); + } + } else { + $phpCodeSnifferConfig[$key] = $value; + } + + if ($temp === false) { + $output = '<'.'?php'."\n".' $phpCodeSnifferConfig = '; + $output .= var_export($phpCodeSnifferConfig, true); + $output .= ";\n?".'>'; + + if (file_put_contents($configFile, $output) === false) { + $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + self::$configDataFile = $configFile; + } + + self::$configData = $phpCodeSnifferConfig; + + // If the installed paths are being set, make sure all known + // standards paths are added to the autoloader. + if ($key === 'installed_paths') { + $installedStandards = Util\Standards::getInstalledStandardDetails(); + foreach ($installedStandards as $name => $details) { + Autoload::addSearchPath($details['path'], $details['namespace']); + } + } + + return true; + + }//end setConfigData() + + + /** + * Get all config data. + * + * @return array + * @see getConfigData() + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read. + */ + public static function getAllConfigData() + { + if (self::$configData !== null) { + return self::$configData; + } + + $path = ''; + if (is_callable('\Phar::running') === true) { + $path = \Phar::running(false); + } + + if ($path !== '') { + $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf'; + } else { + $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf'; + if (is_file($configFile) === false + && strpos('@data_dir@', '@data_dir') === false + ) { + $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf'; + } + } + + if (is_file($configFile) === false) { + self::$configData = []; + return []; + } + + if (Common::isReadable($configFile) === false) { + $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + include $configFile; + self::$configDataFile = $configFile; + self::$configData = $phpCodeSnifferConfig; + return self::$configData; + + }//end getAllConfigData() + + + /** + * Prints out the gathered config data. + * + * @param array $data The config data to print. + * + * @return void + */ + public function printConfigData($data) + { + $max = 0; + $keys = array_keys($data); + foreach ($keys as $key) { + $len = strlen($key); + if (strlen($key) > $max) { + $max = $len; + } + } + + if ($max === 0) { + return; + } + + $max += 2; + ksort($data); + foreach ($data as $name => $value) { + echo str_pad($name.': ', $max).$value.PHP_EOL; + } + + }//end printConfigData() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php new file mode 100644 index 0000000..7732c6d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php @@ -0,0 +1,18 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Exceptions; + +class DeepExitException extends \Exception +{ + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php new file mode 100644 index 0000000..a3d5909 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php @@ -0,0 +1,15 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Exceptions; + +class RuntimeException extends \RuntimeException +{ + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php new file mode 100644 index 0000000..ad25ace --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php @@ -0,0 +1,15 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Exceptions; + +class TokenizerException extends \Exception +{ + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php b/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php new file mode 100644 index 0000000..eb947fd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php @@ -0,0 +1,82 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; + +class DummyFile extends File +{ + + + /** + * Creates a DummyFile object and sets the content. + * + * @param string $content The content of the file. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($content, Ruleset $ruleset, Config $config) + { + $this->setContent($content); + + // See if a filename was defined in the content. + // This is done by including: phpcs_input_file: [file path] + // as the first line of content. + $path = 'STDIN'; + if ($content !== '') { + if (substr($content, 0, 17) === 'phpcs_input_file:') { + $eolPos = strpos($content, $this->eolChar); + $filename = trim(substr($content, 17, ($eolPos - 17))); + $content = substr($content, ($eolPos + strlen($this->eolChar))); + $path = $filename; + + $this->setContent($content); + } + } + + // The CLI arg overrides anything passed in the content. + if ($config->stdinPath !== null) { + $path = $config->stdinPath; + } + + parent::__construct($path, $ruleset, $config); + + }//end __construct() + + + /** + * Set the error, warning, and fixable counts for the file. + * + * @param int $errorCount The number of errors found. + * @param int $warningCount The number of warnings found. + * @param int $fixableCount The number of fixable errors found. + * @param int $fixedCount The number of errors that were fixed. + * + * @return void + */ + public function setErrorCounts($errorCount, $warningCount, $fixableCount, $fixedCount) + { + $this->errorCount = $errorCount; + $this->warningCount = $warningCount; + $this->fixableCount = $fixableCount; + $this->fixedCount = $fixedCount; + + }//end setErrorCounts() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/File.php b/vendor/squizlabs/php_codesniffer/src/Files/File.php new file mode 100644 index 0000000..7b54bea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/File.php @@ -0,0 +1,2890 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Fixer; +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Exceptions\TokenizerException; + +class File +{ + + /** + * The absolute path to the file associated with this object. + * + * @var string + */ + public $path = ''; + + /** + * The content of the file. + * + * @var string + */ + protected $content = ''; + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + + /** + * If TRUE, the entire file is being ignored. + * + * @var boolean + */ + public $ignored = false; + + /** + * The EOL character this file uses. + * + * @var string + */ + public $eolChar = ''; + + /** + * The Fixer object to control fixing errors. + * + * @var \PHP_CodeSniffer\Fixer + */ + public $fixer = null; + + /** + * The tokenizer being used for this file. + * + * @var \PHP_CodeSniffer\Tokenizers\Tokenizer + */ + public $tokenizer = null; + + /** + * The name of the tokenizer being used for this file. + * + * @var string + */ + public $tokenizerType = 'PHP'; + + /** + * Was the file loaded from cache? + * + * If TRUE, the file was loaded from a local cache. + * If FALSE, the file was tokenized and processed fully. + * + * @var boolean + */ + public $fromCache = false; + + /** + * The number of tokens in this file. + * + * Stored here to save calling count() everywhere. + * + * @var integer + */ + public $numTokens = 0; + + /** + * The tokens stack map. + * + * @var array + */ + protected $tokens = []; + + /** + * The errors raised from sniffs. + * + * @var array + * @see getErrors() + */ + protected $errors = []; + + /** + * The warnings raised from sniffs. + * + * @var array + * @see getWarnings() + */ + protected $warnings = []; + + /** + * The metrics recorded by sniffs. + * + * @var array + * @see getMetrics() + */ + protected $metrics = []; + + /** + * The metrics recorded for each token. + * + * Stops the same metric being recorded for the same token twice. + * + * @var array + * @see getMetrics() + */ + private $metricTokens = []; + + /** + * The total number of errors raised. + * + * @var integer + */ + protected $errorCount = 0; + + /** + * The total number of warnings raised. + * + * @var integer + */ + protected $warningCount = 0; + + /** + * The total number of errors and warnings that can be fixed. + * + * @var integer + */ + protected $fixableCount = 0; + + /** + * The total number of errors and warnings that were fixed. + * + * @var integer + */ + protected $fixedCount = 0; + + /** + * TRUE if errors are being replayed from the cache. + * + * @var boolean + */ + protected $replayingErrors = false; + + /** + * An array of sniffs that are being ignored. + * + * @var array + */ + protected $ignoredListeners = []; + + /** + * An array of message codes that are being ignored. + * + * @var array + */ + protected $ignoredCodes = []; + + /** + * An array of sniffs listening to this file's processing. + * + * @var \PHP_CodeSniffer\Sniffs\Sniff[] + */ + protected $listeners = []; + + /** + * The class name of the sniff currently processing the file. + * + * @var string + */ + protected $activeListener = ''; + + /** + * An array of sniffs being processed and how long they took. + * + * @var array + * @see getListenerTimes() + */ + protected $listenerTimes = []; + + /** + * A cache of often used config settings to improve performance. + * + * Storing them here saves 10k+ calls to __get() in the Config class. + * + * @var array + */ + protected $configCache = []; + + + /** + * Constructs a file. + * + * @param string $path The absolute path to the file to process. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($path, Ruleset $ruleset, Config $config) + { + $this->path = $path; + $this->ruleset = $ruleset; + $this->config = $config; + $this->fixer = new Fixer(); + + $parts = explode('.', $path); + $extension = array_pop($parts); + if (isset($config->extensions[$extension]) === true) { + $this->tokenizerType = $config->extensions[$extension]; + } else { + // Revert to default. + $this->tokenizerType = 'PHP'; + } + + $this->configCache['cache'] = $this->config->cache; + $this->configCache['sniffs'] = array_map('strtolower', $this->config->sniffs); + $this->configCache['exclude'] = array_map('strtolower', $this->config->exclude); + $this->configCache['errorSeverity'] = $this->config->errorSeverity; + $this->configCache['warningSeverity'] = $this->config->warningSeverity; + $this->configCache['recordErrors'] = $this->config->recordErrors; + $this->configCache['trackTime'] = $this->config->trackTime; + $this->configCache['ignorePatterns'] = $this->ruleset->ignorePatterns; + $this->configCache['includePatterns'] = $this->ruleset->includePatterns; + + }//end __construct() + + + /** + * Set the content of the file. + * + * Setting the content also calculates the EOL char being used. + * + * @param string $content The file content. + * + * @return void + */ + public function setContent($content) + { + $this->content = $content; + $this->tokens = []; + + try { + $this->eolChar = Util\Common::detectLineEndings($content); + } catch (RuntimeException $e) { + $this->addWarningOnLine($e->getMessage(), 1, 'Internal.DetectLineEndings'); + return; + } + + }//end setContent() + + + /** + * Reloads the content of the file. + * + * By default, we have no idea where our content comes from, + * so we can't do anything. + * + * @return void + */ + public function reloadContent() + { + + }//end reloadContent() + + + /** + * Disables caching of this file. + * + * @return void + */ + public function disableCaching() + { + $this->configCache['cache'] = false; + + }//end disableCaching() + + + /** + * Starts the stack traversal and tells listeners when tokens are found. + * + * @return void + */ + public function process() + { + if ($this->ignored === true) { + return; + } + + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + + $this->parse(); + + // Check if tokenizer errors cause this file to be ignored. + if ($this->ignored === true) { + return; + } + + $this->fixer->startFile($this); + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + echo "\t*** START TOKEN PROCESSING ***".PHP_EOL; + } + + $foundCode = false; + $listenerIgnoreTo = []; + $inTests = defined('PHP_CODESNIFFER_IN_TESTS'); + $checkAnnotations = $this->config->annotations; + $annotationErrors = []; + + // Foreach of the listeners that have registered to listen for this + // token, get them to process it. + foreach ($this->tokens as $stackPtr => $token) { + // Check for ignored lines. + if ($checkAnnotations === true + && ($token['code'] === T_COMMENT + || $token['code'] === T_PHPCS_IGNORE_FILE + || $token['code'] === T_PHPCS_SET + || $token['code'] === T_DOC_COMMENT_STRING + || $token['code'] === T_DOC_COMMENT_TAG + || ($inTests === true && $token['code'] === T_INLINE_HTML)) + ) { + $commentText = ltrim($this->tokens[$stackPtr]['content'], " \t/*#"); + $commentTextLower = strtolower($commentText); + if (strpos($commentText, '@codingStandards') !== false) { + if (strpos($commentText, '@codingStandardsIgnoreFile') !== false) { + // Ignoring the whole file, just a little late. + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + return; + } else if (strpos($commentText, '@codingStandardsChangeSetting') !== false) { + $start = strpos($commentText, '@codingStandardsChangeSetting'); + $comment = substr($commentText, ($start + 30)); + $parts = explode(' ', $comment); + if (count($parts) >= 2) { + $sniffParts = explode('.', $parts[0]); + if (count($sniffParts) >= 3) { + // If the sniff code is not known to us, it has not been registered in this run. + // But don't throw an error as it could be there for a different standard to use. + if (isset($this->ruleset->sniffCodes[$parts[0]]) === true) { + $listenerCode = array_shift($parts); + $propertyCode = array_shift($parts); + $settings = [ + 'value' => rtrim(implode(' ', $parts), " */\r\n"), + 'scope' => 'sniff', + ]; + $listenerClass = $this->ruleset->sniffCodes[$listenerCode]; + $this->ruleset->setSniffProperty($listenerClass, $propertyCode, $settings); + } + } + } + }//end if + } else if (substr($commentTextLower, 0, 16) === 'phpcs:ignorefile' + || substr($commentTextLower, 0, 17) === '@phpcs:ignorefile' + ) { + // Ignoring the whole file, just a little late. + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + return; + } else if (substr($commentTextLower, 0, 9) === 'phpcs:set' + || substr($commentTextLower, 0, 10) === '@phpcs:set' + ) { + if (isset($token['sniffCode']) === true) { + $listenerCode = $token['sniffCode']; + if (isset($this->ruleset->sniffCodes[$listenerCode]) === true) { + $propertyCode = $token['sniffProperty']; + $settings = [ + 'value' => $token['sniffPropertyValue'], + 'scope' => 'sniff', + ]; + $listenerClass = $this->ruleset->sniffCodes[$listenerCode]; + try { + $this->ruleset->setSniffProperty($listenerClass, $propertyCode, $settings); + } catch (RuntimeException $e) { + // Non-existant property being set via an inline annotation. + // This is typically a PHPCS test case file, but we can't throw an error on the annotation + // line as it would get ignored. We also don't want this error to block + // the scan of the current file, so collect these and throw later. + $annotationErrors[] = 'Line '.$token['line'].': '.str_replace('Ruleset invalid. ', '', $e->getMessage()); + } + } + } + }//end if + }//end if + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + $type = $token['type']; + $content = Util\Common::prepareForOutput($token['content']); + echo "\t\tProcess token $stackPtr: $type => $content".PHP_EOL; + } + + if ($token['code'] !== T_INLINE_HTML) { + $foundCode = true; + } + + if (isset($this->ruleset->tokenListeners[$token['code']]) === false) { + continue; + } + + foreach ($this->ruleset->tokenListeners[$token['code']] as $listenerData) { + if (isset($this->ignoredListeners[$listenerData['class']]) === true + || (isset($listenerIgnoreTo[$listenerData['class']]) === true + && $listenerIgnoreTo[$listenerData['class']] > $stackPtr) + ) { + // This sniff is ignoring past this token, or the whole file. + continue; + } + + // Make sure this sniff supports the tokenizer + // we are currently using. + $class = $listenerData['class']; + + if (isset($listenerData['tokenizers'][$this->tokenizerType]) === false) { + continue; + } + + if (trim($this->path, '\'"') !== 'STDIN') { + // If the file path matches one of our ignore patterns, skip it. + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + foreach ($listenerData['ignore'] as $pattern) { + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (DIRECTORY_SEPARATOR === '\\') { + $pattern = str_replace('/', '\\\\', $pattern); + } + + $pattern = '`'.$pattern.'`i'; + if (preg_match($pattern, $this->path) === 1) { + $this->ignoredListeners[$class] = true; + continue(2); + } + } + + // If the file path does not match one of our include patterns, skip it. + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + if (empty($listenerData['include']) === false) { + $included = false; + foreach ($listenerData['include'] as $pattern) { + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (DIRECTORY_SEPARATOR === '\\') { + $pattern = str_replace('/', '\\\\', $pattern); + } + + $pattern = '`'.$pattern.'`i'; + if (preg_match($pattern, $this->path) === 1) { + $included = true; + break; + } + } + + if ($included === false) { + $this->ignoredListeners[$class] = true; + continue; + } + }//end if + }//end if + + $this->activeListener = $class; + + if ($this->configCache['trackTime'] === true) { + $startTime = microtime(true); + } + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + echo "\t\t\tProcessing ".$this->activeListener.'... '; + } + + $ignoreTo = $this->ruleset->sniffs[$class]->process($this, $stackPtr); + if ($ignoreTo !== null) { + $listenerIgnoreTo[$this->activeListener] = $ignoreTo; + } + + if ($this->configCache['trackTime'] === true) { + $timeTaken = (microtime(true) - $startTime); + if (isset($this->listenerTimes[$this->activeListener]) === false) { + $this->listenerTimes[$this->activeListener] = 0; + } + + $this->listenerTimes[$this->activeListener] += $timeTaken; + } + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + $timeTaken = round(($timeTaken), 4); + echo "DONE in $timeTaken seconds".PHP_EOL; + } + + $this->activeListener = ''; + }//end foreach + }//end foreach + + // If short open tags are off but the file being checked uses + // short open tags, the whole content will be inline HTML + // and nothing will be checked. So try and handle this case. + // We don't show this error for STDIN because we can't be sure the content + // actually came directly from the user. It could be something like + // refs from a Git pre-push hook. + if ($foundCode === false && $this->tokenizerType === 'PHP' && $this->path !== 'STDIN') { + $shortTags = (bool) ini_get('short_open_tag'); + if ($shortTags === false) { + $error = 'No PHP code was found in this file and short open tags are not allowed by this install of PHP. This file may be using short open tags but PHP does not allow them.'; + $this->addWarning($error, null, 'Internal.NoCodeFound'); + } + } + + if ($annotationErrors !== []) { + $error = 'Encountered invalid inline phpcs:set annotations. Found:'.PHP_EOL; + $error .= implode(PHP_EOL, $annotationErrors); + + $this->addWarning($error, null, 'Internal.PropertyDoesNotExist'); + } + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + echo "\t*** END TOKEN PROCESSING ***".PHP_EOL; + echo "\t*** START SNIFF PROCESSING REPORT ***".PHP_EOL; + + arsort($this->listenerTimes, SORT_NUMERIC); + foreach ($this->listenerTimes as $listener => $timeTaken) { + echo "\t$listener: ".round(($timeTaken), 4).' secs'.PHP_EOL; + } + + echo "\t*** END SNIFF PROCESSING REPORT ***".PHP_EOL; + } + + $this->fixedCount += $this->fixer->getFixCount(); + + }//end process() + + + /** + * Tokenizes the file and prepares it for the test run. + * + * @return void + */ + public function parse() + { + if (empty($this->tokens) === false) { + // File has already been parsed. + return; + } + + try { + $tokenizerClass = 'PHP_CodeSniffer\Tokenizers\\'.$this->tokenizerType; + $this->tokenizer = new $tokenizerClass($this->content, $this->config, $this->eolChar); + $this->tokens = $this->tokenizer->getTokens(); + } catch (TokenizerException $e) { + $this->ignored = true; + $this->addWarning($e->getMessage(), null, 'Internal.Tokenizer.Exception'); + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo "[$this->tokenizerType => tokenizer error]... "; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + } + + return; + } + + $this->numTokens = count($this->tokens); + + // Check for mixed line endings as these can cause tokenizer errors and we + // should let the user know that the results they get may be incorrect. + // This is done by removing all backslashes, removing the newline char we + // detected, then converting newlines chars into text. If any backslashes + // are left at the end, we have additional newline chars in use. + $contents = str_replace('\\', '', $this->content); + $contents = str_replace($this->eolChar, '', $contents); + $contents = str_replace("\n", '\n', $contents); + $contents = str_replace("\r", '\r', $contents); + if (strpos($contents, '\\') !== false) { + $error = 'File has mixed line endings; this may cause incorrect results'; + $this->addWarningOnLine($error, 1, 'Internal.LineEndings.Mixed'); + } + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + if ($this->numTokens === 0) { + $numLines = 0; + } else { + $numLines = $this->tokens[($this->numTokens - 1)]['line']; + } + + echo "[$this->tokenizerType => $this->numTokens tokens in $numLines lines]... "; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + } + + }//end parse() + + + /** + * Returns the token stack for this file. + * + * @return array + */ + public function getTokens() + { + return $this->tokens; + + }//end getTokens() + + + /** + * Remove vars stored in this file that are no longer required. + * + * @return void + */ + public function cleanUp() + { + $this->listenerTimes = null; + $this->content = null; + $this->tokens = null; + $this->metricTokens = null; + $this->tokenizer = null; + $this->fixer = null; + $this->config = null; + $this->ruleset = null; + + }//end cleanUp() + + + /** + * Records an error against a specific token in the file. + * + * @param string $error The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the error be fixed by the sniff? + * + * @return boolean + */ + public function addError( + $error, + $stackPtr, + $code, + $data=[], + $severity=0, + $fixable=false + ) { + if ($stackPtr === null) { + $line = 1; + $column = 1; + } else { + $line = $this->tokens[$stackPtr]['line']; + $column = $this->tokens[$stackPtr]['column']; + } + + return $this->addMessage(true, $error, $line, $column, $code, $data, $severity, $fixable); + + }//end addError() + + + /** + * Records a warning against a specific token in the file. + * + * @param string $warning The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the warning be fixed by the sniff? + * + * @return boolean + */ + public function addWarning( + $warning, + $stackPtr, + $code, + $data=[], + $severity=0, + $fixable=false + ) { + if ($stackPtr === null) { + $line = 1; + $column = 1; + } else { + $line = $this->tokens[$stackPtr]['line']; + $column = $this->tokens[$stackPtr]['column']; + } + + return $this->addMessage(false, $warning, $line, $column, $code, $data, $severity, $fixable); + + }//end addWarning() + + + /** + * Records an error against a specific line in the file. + * + * @param string $error The error message. + * @param int $line The line on which the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addErrorOnLine( + $error, + $line, + $code, + $data=[], + $severity=0 + ) { + return $this->addMessage(true, $error, $line, 1, $code, $data, $severity, false); + + }//end addErrorOnLine() + + + /** + * Records a warning against a specific line in the file. + * + * @param string $warning The error message. + * @param int $line The line on which the warning occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 will + * will be converted into the default severity level. + * + * @return boolean + */ + public function addWarningOnLine( + $warning, + $line, + $code, + $data=[], + $severity=0 + ) { + return $this->addMessage(false, $warning, $line, 1, $code, $data, $severity, false); + + }//end addWarningOnLine() + + + /** + * Records a fixable error against a specific token in the file. + * + * Returns true if the error was recorded and should be fixed. + * + * @param string $error The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addFixableError( + $error, + $stackPtr, + $code, + $data=[], + $severity=0 + ) { + $recorded = $this->addError($error, $stackPtr, $code, $data, $severity, true); + if ($recorded === true && $this->fixer->enabled === true) { + return true; + } + + return false; + + }//end addFixableError() + + + /** + * Records a fixable warning against a specific token in the file. + * + * Returns true if the warning was recorded and should be fixed. + * + * @param string $warning The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addFixableWarning( + $warning, + $stackPtr, + $code, + $data=[], + $severity=0 + ) { + $recorded = $this->addWarning($warning, $stackPtr, $code, $data, $severity, true); + if ($recorded === true && $this->fixer->enabled === true) { + return true; + } + + return false; + + }//end addFixableWarning() + + + /** + * Adds an error to the error stack. + * + * @param boolean $error Is this an error message? + * @param string $message The text of the message. + * @param int $line The line on which the message occurred. + * @param int $column The column at which the message occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the message. + * @param int $severity The severity level for this message. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the problem be fixed by the sniff? + * + * @return boolean + */ + protected function addMessage($error, $message, $line, $column, $code, $data, $severity, $fixable) + { + // Check if this line is ignoring all message codes. + if (isset($this->tokenizer->ignoredLines[$line]['.all']) === true) { + return false; + } + + // Work out which sniff generated the message. + $parts = explode('.', $code); + if ($parts[0] === 'Internal') { + // An internal message. + $listenerCode = Util\Common::getSniffCode($this->activeListener); + $sniffCode = $code; + $checkCodes = [$sniffCode]; + } else { + if ($parts[0] !== $code) { + // The full message code has been passed in. + $sniffCode = $code; + $listenerCode = substr($sniffCode, 0, strrpos($sniffCode, '.')); + } else { + $listenerCode = Util\Common::getSniffCode($this->activeListener); + $sniffCode = $listenerCode.'.'.$code; + $parts = explode('.', $sniffCode); + } + + $checkCodes = [ + $sniffCode, + $parts[0].'.'.$parts[1].'.'.$parts[2], + $parts[0].'.'.$parts[1], + $parts[0], + ]; + }//end if + + if (isset($this->tokenizer->ignoredLines[$line]) === true) { + // Check if this line is ignoring this specific message. + $ignored = false; + foreach ($checkCodes as $checkCode) { + if (isset($this->tokenizer->ignoredLines[$line][$checkCode]) === true) { + $ignored = true; + break; + } + } + + // If it is ignored, make sure there is no exception in place. + if ($ignored === true + && isset($this->tokenizer->ignoredLines[$line]['.except']) === true + ) { + foreach ($checkCodes as $checkCode) { + if (isset($this->tokenizer->ignoredLines[$line]['.except'][$checkCode]) === true) { + $ignored = false; + break; + } + } + } + + if ($ignored === true) { + return false; + } + }//end if + + $includeAll = true; + if ($this->configCache['cache'] === false + || $this->configCache['recordErrors'] === false + ) { + $includeAll = false; + } + + // Filter out any messages for sniffs that shouldn't have run + // due to the use of the --sniffs command line argument. + if ($includeAll === false + && ((empty($this->configCache['sniffs']) === false + && in_array(strtolower($listenerCode), $this->configCache['sniffs'], true) === false) + || (empty($this->configCache['exclude']) === false + && in_array(strtolower($listenerCode), $this->configCache['exclude'], true) === true)) + ) { + return false; + } + + // If we know this sniff code is being ignored for this file, return early. + foreach ($checkCodes as $checkCode) { + if (isset($this->ignoredCodes[$checkCode]) === true) { + return false; + } + } + + $oppositeType = 'warning'; + if ($error === false) { + $oppositeType = 'error'; + } + + foreach ($checkCodes as $checkCode) { + // Make sure this message type has not been set to the opposite message type. + if (isset($this->ruleset->ruleset[$checkCode]['type']) === true + && $this->ruleset->ruleset[$checkCode]['type'] === $oppositeType + ) { + $error = !$error; + break; + } + } + + if ($error === true) { + $configSeverity = $this->configCache['errorSeverity']; + $messageCount = &$this->errorCount; + $messages = &$this->errors; + } else { + $configSeverity = $this->configCache['warningSeverity']; + $messageCount = &$this->warningCount; + $messages = &$this->warnings; + } + + if ($includeAll === false && $configSeverity === 0) { + // Don't bother doing any processing as these messages are just going to + // be hidden in the reports anyway. + return false; + } + + if ($severity === 0) { + $severity = 5; + } + + foreach ($checkCodes as $checkCode) { + // Make sure we are interested in this severity level. + if (isset($this->ruleset->ruleset[$checkCode]['severity']) === true) { + $severity = $this->ruleset->ruleset[$checkCode]['severity']; + break; + } + } + + if ($includeAll === false && $configSeverity > $severity) { + return false; + } + + // Make sure we are not ignoring this file. + $included = null; + if (trim($this->path, '\'"') === 'STDIN') { + $included = true; + } else { + foreach ($checkCodes as $checkCode) { + $patterns = null; + + if (isset($this->configCache['includePatterns'][$checkCode]) === true) { + $patterns = $this->configCache['includePatterns'][$checkCode]; + $excluding = false; + } else if (isset($this->configCache['ignorePatterns'][$checkCode]) === true) { + $patterns = $this->configCache['ignorePatterns'][$checkCode]; + $excluding = true; + } + + if ($patterns === null) { + continue; + } + + foreach ($patterns as $pattern => $type) { + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + $replacements = [ + '\\,' => ',', + '*' => '.*', + ]; + + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (DIRECTORY_SEPARATOR === '\\') { + $replacements['/'] = '\\\\'; + } + + $pattern = '`'.strtr($pattern, $replacements).'`i'; + $matched = preg_match($pattern, $this->path); + + if ($matched === 0) { + if ($excluding === false && $included === null) { + // This file path is not being included. + $included = false; + } + + continue; + } + + if ($excluding === true) { + // This file path is being excluded. + $this->ignoredCodes[$checkCode] = true; + return false; + } + + // This file path is being included. + $included = true; + break; + }//end foreach + }//end foreach + }//end if + + if ($included === false) { + // There were include rules set, but this file + // path didn't match any of them. + return false; + } + + $messageCount++; + if ($fixable === true) { + $this->fixableCount++; + } + + if ($this->configCache['recordErrors'] === false + && $includeAll === false + ) { + return true; + } + + // See if there is a custom error message format to use. + // But don't do this if we are replaying errors because replayed + // errors have already used the custom format and have had their + // data replaced. + if ($this->replayingErrors === false + && isset($this->ruleset->ruleset[$sniffCode]['message']) === true + ) { + $message = $this->ruleset->ruleset[$sniffCode]['message']; + } + + if (empty($data) === false) { + $message = vsprintf($message, $data); + } + + if (isset($messages[$line]) === false) { + $messages[$line] = []; + } + + if (isset($messages[$line][$column]) === false) { + $messages[$line][$column] = []; + } + + $messages[$line][$column][] = [ + 'message' => $message, + 'source' => $sniffCode, + 'listener' => $this->activeListener, + 'severity' => $severity, + 'fixable' => $fixable, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1 + && $this->fixer->enabled === true + && $fixable === true + ) { + @ob_end_clean(); + echo "\tE: [Line $line] $message ($sniffCode)".PHP_EOL; + ob_start(); + } + + return true; + + }//end addMessage() + + + /** + * Record a metric about the file being examined. + * + * @param int $stackPtr The stack position where the metric was recorded. + * @param string $metric The name of the metric being recorded. + * @param string $value The value of the metric being recorded. + * + * @return boolean + */ + public function recordMetric($stackPtr, $metric, $value) + { + if (isset($this->metrics[$metric]) === false) { + $this->metrics[$metric] = ['values' => [$value => 1]]; + $this->metricTokens[$metric][$stackPtr] = true; + } else if (isset($this->metricTokens[$metric][$stackPtr]) === false) { + $this->metricTokens[$metric][$stackPtr] = true; + if (isset($this->metrics[$metric]['values'][$value]) === false) { + $this->metrics[$metric]['values'][$value] = 1; + } else { + $this->metrics[$metric]['values'][$value]++; + } + } + + return true; + + }//end recordMetric() + + + /** + * Returns the number of errors raised. + * + * @return int + */ + public function getErrorCount() + { + return $this->errorCount; + + }//end getErrorCount() + + + /** + * Returns the number of warnings raised. + * + * @return int + */ + public function getWarningCount() + { + return $this->warningCount; + + }//end getWarningCount() + + + /** + * Returns the number of fixable errors/warnings raised. + * + * @return int + */ + public function getFixableCount() + { + return $this->fixableCount; + + }//end getFixableCount() + + + /** + * Returns the number of fixed errors/warnings. + * + * @return int + */ + public function getFixedCount() + { + return $this->fixedCount; + + }//end getFixedCount() + + + /** + * Returns the list of ignored lines. + * + * @return array + */ + public function getIgnoredLines() + { + return $this->tokenizer->ignoredLines; + + }//end getIgnoredLines() + + + /** + * Returns the errors raised from processing this file. + * + * @return array + */ + public function getErrors() + { + return $this->errors; + + }//end getErrors() + + + /** + * Returns the warnings raised from processing this file. + * + * @return array + */ + public function getWarnings() + { + return $this->warnings; + + }//end getWarnings() + + + /** + * Returns the metrics found while processing this file. + * + * @return array + */ + public function getMetrics() + { + return $this->metrics; + + }//end getMetrics() + + + /** + * Returns the time taken processing this file for each invoked sniff. + * + * @return array + */ + public function getListenerTimes() + { + return $this->listenerTimes; + + }//end getListenerTimes() + + + /** + * Returns the absolute filename of this file. + * + * @return string + */ + public function getFilename() + { + return $this->path; + + }//end getFilename() + + + /** + * Returns the declaration name for classes, interfaces, traits, enums, and functions. + * + * @param int $stackPtr The position of the declaration token which + * declared the class, interface, trait, or function. + * + * @return string|null The name of the class, interface, trait, or function; + * or NULL if the function or class is anonymous. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified token is not of type + * T_FUNCTION, T_CLASS, T_ANON_CLASS, + * T_CLOSURE, T_TRAIT, T_ENUM, or T_INTERFACE. + */ + public function getDeclarationName($stackPtr) + { + $tokenCode = $this->tokens[$stackPtr]['code']; + + if ($tokenCode === T_ANON_CLASS || $tokenCode === T_CLOSURE) { + return null; + } + + if ($tokenCode !== T_FUNCTION + && $tokenCode !== T_CLASS + && $tokenCode !== T_INTERFACE + && $tokenCode !== T_TRAIT + && $tokenCode !== T_ENUM + ) { + throw new RuntimeException('Token type "'.$this->tokens[$stackPtr]['type'].'" is not T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM'); + } + + if ($tokenCode === T_FUNCTION + && strtolower($this->tokens[$stackPtr]['content']) !== 'function' + ) { + // This is a function declared without the "function" keyword. + // So this token is the function name. + return $this->tokens[$stackPtr]['content']; + } + + $content = null; + for ($i = $stackPtr; $i < $this->numTokens; $i++) { + if ($this->tokens[$i]['code'] === T_STRING) { + $content = $this->tokens[$i]['content']; + break; + } + } + + return $content; + + }//end getDeclarationName() + + + /** + * Returns the method parameters for the specified function token. + * + * Also supports passing in a USE token for a closure use group. + * + * Each parameter is in the following format: + * + * + * 0 => array( + * 'name' => string, // The variable name. + * 'token' => integer, // The stack pointer to the variable name. + * 'content' => string, // The full content of the variable definition. + * 'has_attributes' => boolean, // Does the parameter have one or more attributes attached ? + * 'pass_by_reference' => boolean, // Is the variable passed by reference? + * 'reference_token' => integer|false, // The stack pointer to the reference operator + * // or FALSE if the param is not passed by reference. + * 'variable_length' => boolean, // Is the param of variable length through use of `...` ? + * 'variadic_token' => integer|false, // The stack pointer to the ... operator + * // or FALSE if the param is not variable length. + * 'type_hint' => string, // The type hint for the variable. + * 'type_hint_token' => integer|false, // The stack pointer to the start of the type hint + * // or FALSE if there is no type hint. + * 'type_hint_end_token' => integer|false, // The stack pointer to the end of the type hint + * // or FALSE if there is no type hint. + * 'nullable_type' => boolean, // TRUE if the type is preceded by the nullability + * // operator. + * 'comma_token' => integer|false, // The stack pointer to the comma after the param + * // or FALSE if this is the last param. + * ) + * + * + * Parameters with default values have additional array indexes of: + * 'default' => string, // The full content of the default value. + * 'default_token' => integer, // The stack pointer to the start of the default value. + * 'default_equal_token' => integer, // The stack pointer to the equals sign. + * + * Parameters declared using PHP 8 constructor property promotion, have these additional array indexes: + * 'property_visibility' => string, // The property visibility as declared. + * 'visibility_token' => integer|false, // The stack pointer to the visibility modifier token + * // or FALSE if the visibility is not explicitly declared. + * 'property_readonly' => boolean, // TRUE if the readonly keyword was found. + * 'readonly_token' => integer, // The stack pointer to the readonly modifier token. + * // This index will only be set if the property is readonly. + * + * @param int $stackPtr The position in the stack of the function token + * to acquire the parameters for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified $stackPtr is not of + * type T_FUNCTION, T_CLOSURE, T_USE, + * or T_FN. + */ + public function getMethodParameters($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== T_FUNCTION + && $this->tokens[$stackPtr]['code'] !== T_CLOSURE + && $this->tokens[$stackPtr]['code'] !== T_USE + && $this->tokens[$stackPtr]['code'] !== T_FN + ) { + throw new RuntimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_USE or T_FN'); + } + + if ($this->tokens[$stackPtr]['code'] === T_USE) { + $opener = $this->findNext(T_OPEN_PARENTHESIS, ($stackPtr + 1)); + if ($opener === false || isset($this->tokens[$opener]['parenthesis_owner']) === true) { + throw new RuntimeException('$stackPtr was not a valid T_USE'); + } + } else { + if (isset($this->tokens[$stackPtr]['parenthesis_opener']) === false) { + // Live coding or syntax error, so no params to find. + return []; + } + + $opener = $this->tokens[$stackPtr]['parenthesis_opener']; + } + + if (isset($this->tokens[$opener]['parenthesis_closer']) === false) { + // Live coding or syntax error, so no params to find. + return []; + } + + $closer = $this->tokens[$opener]['parenthesis_closer']; + + $vars = []; + $currVar = null; + $paramStart = ($opener + 1); + $defaultStart = null; + $equalToken = null; + $paramCount = 0; + $hasAttributes = false; + $passByReference = false; + $referenceToken = false; + $variableLength = false; + $variadicToken = false; + $typeHint = ''; + $typeHintToken = false; + $typeHintEndToken = false; + $nullableType = false; + $visibilityToken = null; + $readonlyToken = null; + + for ($i = $paramStart; $i <= $closer; $i++) { + // Check to see if this token has a parenthesis or bracket opener. If it does + // it's likely to be an array which might have arguments in it. This + // could cause problems in our parsing below, so lets just skip to the + // end of it. + if (isset($this->tokens[$i]['parenthesis_opener']) === true) { + // Don't do this if it's the close parenthesis for the method. + if ($i !== $this->tokens[$i]['parenthesis_closer']) { + $i = $this->tokens[$i]['parenthesis_closer']; + continue; + } + } + + if (isset($this->tokens[$i]['bracket_opener']) === true) { + if ($i !== $this->tokens[$i]['bracket_closer']) { + $i = $this->tokens[$i]['bracket_closer']; + continue; + } + } + + switch ($this->tokens[$i]['code']) { + case T_ATTRIBUTE: + $hasAttributes = true; + + // Skip to the end of the attribute. + $i = $this->tokens[$i]['attribute_closer']; + break; + case T_BITWISE_AND: + if ($defaultStart === null) { + $passByReference = true; + $referenceToken = $i; + } + break; + case T_VARIABLE: + $currVar = $i; + break; + case T_ELLIPSIS: + $variableLength = true; + $variadicToken = $i; + break; + case T_CALLABLE: + if ($typeHintToken === false) { + $typeHintToken = $i; + } + + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + break; + case T_SELF: + case T_PARENT: + case T_STATIC: + // Self and parent are valid, static invalid, but was probably intended as type hint. + if (isset($defaultStart) === false) { + if ($typeHintToken === false) { + $typeHintToken = $i; + } + + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case T_STRING: + // This is a string, so it may be a type hint, but it could + // also be a constant used as a default value. + $prevComma = false; + for ($t = $i; $t >= $opener; $t--) { + if ($this->tokens[$t]['code'] === T_COMMA) { + $prevComma = $t; + break; + } + } + + if ($prevComma !== false) { + $nextEquals = false; + for ($t = $prevComma; $t < $i; $t++) { + if ($this->tokens[$t]['code'] === T_EQUAL) { + $nextEquals = $t; + break; + } + } + + if ($nextEquals !== false) { + break; + } + } + + if ($defaultStart === null) { + if ($typeHintToken === false) { + $typeHintToken = $i; + } + + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case T_NAMESPACE: + case T_NS_SEPARATOR: + case T_TYPE_UNION: + case T_TYPE_INTERSECTION: + case T_FALSE: + case T_TRUE: + case T_NULL: + // Part of a type hint or default value. + if ($defaultStart === null) { + if ($typeHintToken === false) { + $typeHintToken = $i; + } + + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case T_NULLABLE: + if ($defaultStart === null) { + $nullableType = true; + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case T_PUBLIC: + case T_PROTECTED: + case T_PRIVATE: + if ($defaultStart === null) { + $visibilityToken = $i; + } + break; + case T_READONLY: + if ($defaultStart === null) { + $readonlyToken = $i; + } + break; + case T_CLOSE_PARENTHESIS: + case T_COMMA: + // If it's null, then there must be no parameters for this + // method. + if ($currVar === null) { + continue 2; + } + + $vars[$paramCount] = []; + $vars[$paramCount]['token'] = $currVar; + $vars[$paramCount]['name'] = $this->tokens[$currVar]['content']; + $vars[$paramCount]['content'] = trim($this->getTokensAsString($paramStart, ($i - $paramStart))); + + if ($defaultStart !== null) { + $vars[$paramCount]['default'] = trim($this->getTokensAsString($defaultStart, ($i - $defaultStart))); + $vars[$paramCount]['default_token'] = $defaultStart; + $vars[$paramCount]['default_equal_token'] = $equalToken; + } + + $vars[$paramCount]['has_attributes'] = $hasAttributes; + $vars[$paramCount]['pass_by_reference'] = $passByReference; + $vars[$paramCount]['reference_token'] = $referenceToken; + $vars[$paramCount]['variable_length'] = $variableLength; + $vars[$paramCount]['variadic_token'] = $variadicToken; + $vars[$paramCount]['type_hint'] = $typeHint; + $vars[$paramCount]['type_hint_token'] = $typeHintToken; + $vars[$paramCount]['type_hint_end_token'] = $typeHintEndToken; + $vars[$paramCount]['nullable_type'] = $nullableType; + + if ($visibilityToken !== null || $readonlyToken !== null) { + $vars[$paramCount]['property_visibility'] = 'public'; + $vars[$paramCount]['visibility_token'] = false; + $vars[$paramCount]['property_readonly'] = false; + + if ($visibilityToken !== null) { + $vars[$paramCount]['property_visibility'] = $this->tokens[$visibilityToken]['content']; + $vars[$paramCount]['visibility_token'] = $visibilityToken; + } + + if ($readonlyToken !== null) { + $vars[$paramCount]['property_readonly'] = true; + $vars[$paramCount]['readonly_token'] = $readonlyToken; + } + } + + if ($this->tokens[$i]['code'] === T_COMMA) { + $vars[$paramCount]['comma_token'] = $i; + } else { + $vars[$paramCount]['comma_token'] = false; + } + + // Reset the vars, as we are about to process the next parameter. + $currVar = null; + $paramStart = ($i + 1); + $defaultStart = null; + $equalToken = null; + $hasAttributes = false; + $passByReference = false; + $referenceToken = false; + $variableLength = false; + $variadicToken = false; + $typeHint = ''; + $typeHintToken = false; + $typeHintEndToken = false; + $nullableType = false; + $visibilityToken = null; + $readonlyToken = null; + + $paramCount++; + break; + case T_EQUAL: + $defaultStart = $this->findNext(Util\Tokens::$emptyTokens, ($i + 1), null, true); + $equalToken = $i; + break; + }//end switch + }//end for + + return $vars; + + }//end getMethodParameters() + + + /** + * Returns the visibility and implementation properties of a method. + * + * The format of the return value is: + * + * array( + * 'scope' => string, // Public, private, or protected + * 'scope_specified' => boolean, // TRUE if the scope keyword was found. + * 'return_type' => string, // The return type of the method. + * 'return_type_token' => integer|false, // The stack pointer to the start of the return type + * // or FALSE if there is no return type. + * 'return_type_end_token' => integer|false, // The stack pointer to the end of the return type + * // or FALSE if there is no return type. + * 'nullable_return_type' => boolean, // TRUE if the return type is preceded by the + * // nullability operator. + * 'is_abstract' => boolean, // TRUE if the abstract keyword was found. + * 'is_final' => boolean, // TRUE if the final keyword was found. + * 'is_static' => boolean, // TRUE if the static keyword was found. + * 'has_body' => boolean, // TRUE if the method has a body + * ); + * + * + * @param int $stackPtr The position in the stack of the function token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_FUNCTION, T_CLOSURE, or T_FN token. + */ + public function getMethodProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== T_FUNCTION + && $this->tokens[$stackPtr]['code'] !== T_CLOSURE + && $this->tokens[$stackPtr]['code'] !== T_FN + ) { + throw new RuntimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_FN'); + } + + if ($this->tokens[$stackPtr]['code'] === T_FUNCTION) { + $valid = [ + T_PUBLIC => T_PUBLIC, + T_PRIVATE => T_PRIVATE, + T_PROTECTED => T_PROTECTED, + T_STATIC => T_STATIC, + T_FINAL => T_FINAL, + T_ABSTRACT => T_ABSTRACT, + T_WHITESPACE => T_WHITESPACE, + T_COMMENT => T_COMMENT, + T_DOC_COMMENT => T_DOC_COMMENT, + ]; + } else { + $valid = [ + T_STATIC => T_STATIC, + T_WHITESPACE => T_WHITESPACE, + T_COMMENT => T_COMMENT, + T_DOC_COMMENT => T_DOC_COMMENT, + ]; + } + + $scope = 'public'; + $scopeSpecified = false; + $isAbstract = false; + $isFinal = false; + $isStatic = false; + + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if (isset($valid[$this->tokens[$i]['code']]) === false) { + break; + } + + switch ($this->tokens[$i]['code']) { + case T_PUBLIC: + $scope = 'public'; + $scopeSpecified = true; + break; + case T_PRIVATE: + $scope = 'private'; + $scopeSpecified = true; + break; + case T_PROTECTED: + $scope = 'protected'; + $scopeSpecified = true; + break; + case T_ABSTRACT: + $isAbstract = true; + break; + case T_FINAL: + $isFinal = true; + break; + case T_STATIC: + $isStatic = true; + break; + }//end switch + }//end for + + $returnType = ''; + $returnTypeToken = false; + $returnTypeEndToken = false; + $nullableReturnType = false; + $hasBody = true; + + if (isset($this->tokens[$stackPtr]['parenthesis_closer']) === true) { + $scopeOpener = null; + if (isset($this->tokens[$stackPtr]['scope_opener']) === true) { + $scopeOpener = $this->tokens[$stackPtr]['scope_opener']; + } + + $valid = [ + T_STRING => T_STRING, + T_CALLABLE => T_CALLABLE, + T_SELF => T_SELF, + T_PARENT => T_PARENT, + T_STATIC => T_STATIC, + T_FALSE => T_FALSE, + T_TRUE => T_TRUE, + T_NULL => T_NULL, + T_NAMESPACE => T_NAMESPACE, + T_NS_SEPARATOR => T_NS_SEPARATOR, + T_TYPE_UNION => T_TYPE_UNION, + T_TYPE_INTERSECTION => T_TYPE_INTERSECTION, + ]; + + for ($i = $this->tokens[$stackPtr]['parenthesis_closer']; $i < $this->numTokens; $i++) { + if (($scopeOpener === null && $this->tokens[$i]['code'] === T_SEMICOLON) + || ($scopeOpener !== null && $i === $scopeOpener) + ) { + // End of function definition. + break; + } + + if ($this->tokens[$i]['code'] === T_NULLABLE) { + $nullableReturnType = true; + } + + if (isset($valid[$this->tokens[$i]['code']]) === true) { + if ($returnTypeToken === false) { + $returnTypeToken = $i; + } + + $returnType .= $this->tokens[$i]['content']; + $returnTypeEndToken = $i; + } + }//end for + + if ($this->tokens[$stackPtr]['code'] === T_FN) { + $bodyToken = T_FN_ARROW; + } else { + $bodyToken = T_OPEN_CURLY_BRACKET; + } + + $end = $this->findNext([$bodyToken, T_SEMICOLON], $this->tokens[$stackPtr]['parenthesis_closer']); + $hasBody = $this->tokens[$end]['code'] === $bodyToken; + }//end if + + if ($returnType !== '' && $nullableReturnType === true) { + $returnType = '?'.$returnType; + } + + return [ + 'scope' => $scope, + 'scope_specified' => $scopeSpecified, + 'return_type' => $returnType, + 'return_type_token' => $returnTypeToken, + 'return_type_end_token' => $returnTypeEndToken, + 'nullable_return_type' => $nullableReturnType, + 'is_abstract' => $isAbstract, + 'is_final' => $isFinal, + 'is_static' => $isStatic, + 'has_body' => $hasBody, + ]; + + }//end getMethodProperties() + + + /** + * Returns the visibility and implementation properties of a class member var. + * + * The format of the return value is: + * + * + * array( + * 'scope' => string, // Public, private, or protected. + * 'scope_specified' => boolean, // TRUE if the scope was explicitly specified. + * 'is_static' => boolean, // TRUE if the static keyword was found. + * 'is_readonly' => boolean, // TRUE if the readonly keyword was found. + * 'type' => string, // The type of the var (empty if no type specified). + * 'type_token' => integer|false, // The stack pointer to the start of the type + * // or FALSE if there is no type. + * 'type_end_token' => integer|false, // The stack pointer to the end of the type + * // or FALSE if there is no type. + * 'nullable_type' => boolean, // TRUE if the type is preceded by the nullability + * // operator. + * ); + * + * + * @param int $stackPtr The position in the stack of the T_VARIABLE token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_VARIABLE token, or if the position is not + * a class member variable. + */ + public function getMemberProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== T_VARIABLE) { + throw new RuntimeException('$stackPtr must be of type T_VARIABLE'); + } + + $conditions = array_keys($this->tokens[$stackPtr]['conditions']); + $ptr = array_pop($conditions); + if (isset($this->tokens[$ptr]) === false + || ($this->tokens[$ptr]['code'] !== T_CLASS + && $this->tokens[$ptr]['code'] !== T_ANON_CLASS + && $this->tokens[$ptr]['code'] !== T_TRAIT) + ) { + if (isset($this->tokens[$ptr]) === true + && ($this->tokens[$ptr]['code'] === T_INTERFACE + || $this->tokens[$ptr]['code'] === T_ENUM) + ) { + // T_VARIABLEs in interfaces/enums can actually be method arguments + // but they won't be seen as being inside the method because there + // are no scope openers and closers for abstract methods. If it is in + // parentheses, we can be pretty sure it is a method argument. + if (isset($this->tokens[$stackPtr]['nested_parenthesis']) === false + || empty($this->tokens[$stackPtr]['nested_parenthesis']) === true + ) { + $error = 'Possible parse error: %ss may not include member vars'; + $code = sprintf('Internal.ParseError.%sHasMemberVar', ucfirst($this->tokens[$ptr]['content'])); + $data = [strtolower($this->tokens[$ptr]['content'])]; + $this->addWarning($error, $stackPtr, $code, $data); + return []; + } + } else { + throw new RuntimeException('$stackPtr is not a class member var'); + } + }//end if + + // Make sure it's not a method parameter. + if (empty($this->tokens[$stackPtr]['nested_parenthesis']) === false) { + $parenthesis = array_keys($this->tokens[$stackPtr]['nested_parenthesis']); + $deepestOpen = array_pop($parenthesis); + if ($deepestOpen > $ptr + && isset($this->tokens[$deepestOpen]['parenthesis_owner']) === true + && $this->tokens[$this->tokens[$deepestOpen]['parenthesis_owner']]['code'] === T_FUNCTION + ) { + throw new RuntimeException('$stackPtr is not a class member var'); + } + } + + $valid = [ + T_PUBLIC => T_PUBLIC, + T_PRIVATE => T_PRIVATE, + T_PROTECTED => T_PROTECTED, + T_STATIC => T_STATIC, + T_VAR => T_VAR, + T_READONLY => T_READONLY, + ]; + + $valid += Util\Tokens::$emptyTokens; + + $scope = 'public'; + $scopeSpecified = false; + $isStatic = false; + $isReadonly = false; + + $startOfStatement = $this->findPrevious( + [ + T_SEMICOLON, + T_OPEN_CURLY_BRACKET, + T_CLOSE_CURLY_BRACKET, + T_ATTRIBUTE_END, + ], + ($stackPtr - 1) + ); + + for ($i = ($startOfStatement + 1); $i < $stackPtr; $i++) { + if (isset($valid[$this->tokens[$i]['code']]) === false) { + break; + } + + switch ($this->tokens[$i]['code']) { + case T_PUBLIC: + $scope = 'public'; + $scopeSpecified = true; + break; + case T_PRIVATE: + $scope = 'private'; + $scopeSpecified = true; + break; + case T_PROTECTED: + $scope = 'protected'; + $scopeSpecified = true; + break; + case T_STATIC: + $isStatic = true; + break; + case T_READONLY: + $isReadonly = true; + break; + } + }//end for + + $type = ''; + $typeToken = false; + $typeEndToken = false; + $nullableType = false; + + if ($i < $stackPtr) { + // We've found a type. + $valid = [ + T_STRING => T_STRING, + T_CALLABLE => T_CALLABLE, + T_SELF => T_SELF, + T_PARENT => T_PARENT, + T_FALSE => T_FALSE, + T_TRUE => T_TRUE, + T_NULL => T_NULL, + T_NAMESPACE => T_NAMESPACE, + T_NS_SEPARATOR => T_NS_SEPARATOR, + T_TYPE_UNION => T_TYPE_UNION, + T_TYPE_INTERSECTION => T_TYPE_INTERSECTION, + ]; + + for ($i; $i < $stackPtr; $i++) { + if ($this->tokens[$i]['code'] === T_VARIABLE) { + // Hit another variable in a group definition. + break; + } + + if ($this->tokens[$i]['code'] === T_NULLABLE) { + $nullableType = true; + } + + if (isset($valid[$this->tokens[$i]['code']]) === true) { + $typeEndToken = $i; + if ($typeToken === false) { + $typeToken = $i; + } + + $type .= $this->tokens[$i]['content']; + } + } + + if ($type !== '' && $nullableType === true) { + $type = '?'.$type; + } + }//end if + + return [ + 'scope' => $scope, + 'scope_specified' => $scopeSpecified, + 'is_static' => $isStatic, + 'is_readonly' => $isReadonly, + 'type' => $type, + 'type_token' => $typeToken, + 'type_end_token' => $typeEndToken, + 'nullable_type' => $nullableType, + ]; + + }//end getMemberProperties() + + + /** + * Returns the visibility and implementation properties of a class. + * + * The format of the return value is: + * + * array( + * 'is_abstract' => boolean, // TRUE if the abstract keyword was found. + * 'is_final' => boolean, // TRUE if the final keyword was found. + * 'is_readonly' => boolean, // TRUE if the readonly keyword was found. + * ); + * + * + * @param int $stackPtr The position in the stack of the T_CLASS token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_CLASS token. + */ + public function getClassProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== T_CLASS) { + throw new RuntimeException('$stackPtr must be of type T_CLASS'); + } + + $valid = [ + T_FINAL => T_FINAL, + T_ABSTRACT => T_ABSTRACT, + T_READONLY => T_READONLY, + T_WHITESPACE => T_WHITESPACE, + T_COMMENT => T_COMMENT, + T_DOC_COMMENT => T_DOC_COMMENT, + ]; + + $isAbstract = false; + $isFinal = false; + $isReadonly = false; + + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if (isset($valid[$this->tokens[$i]['code']]) === false) { + break; + } + + switch ($this->tokens[$i]['code']) { + case T_ABSTRACT: + $isAbstract = true; + break; + + case T_FINAL: + $isFinal = true; + break; + + case T_READONLY: + $isReadonly = true; + break; + } + }//end for + + return [ + 'is_abstract' => $isAbstract, + 'is_final' => $isFinal, + 'is_readonly' => $isReadonly, + ]; + + }//end getClassProperties() + + + /** + * Determine if the passed token is a reference operator. + * + * Returns true if the specified token position represents a reference. + * Returns false if the token represents a bitwise operator. + * + * @param int $stackPtr The position of the T_BITWISE_AND token. + * + * @return boolean + */ + public function isReference($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== T_BITWISE_AND) { + return false; + } + + $tokenBefore = $this->findPrevious( + Util\Tokens::$emptyTokens, + ($stackPtr - 1), + null, + true + ); + + if ($this->tokens[$tokenBefore]['code'] === T_FUNCTION + || $this->tokens[$tokenBefore]['code'] === T_CLOSURE + || $this->tokens[$tokenBefore]['code'] === T_FN + ) { + // Function returns a reference. + return true; + } + + if ($this->tokens[$tokenBefore]['code'] === T_DOUBLE_ARROW) { + // Inside a foreach loop or array assignment, this is a reference. + return true; + } + + if ($this->tokens[$tokenBefore]['code'] === T_AS) { + // Inside a foreach loop, this is a reference. + return true; + } + + if (isset(Util\Tokens::$assignmentTokens[$this->tokens[$tokenBefore]['code']]) === true) { + // This is directly after an assignment. It's a reference. Even if + // it is part of an operation, the other tests will handle it. + return true; + } + + $tokenAfter = $this->findNext( + Util\Tokens::$emptyTokens, + ($stackPtr + 1), + null, + true + ); + + if ($this->tokens[$tokenAfter]['code'] === T_NEW) { + return true; + } + + if (isset($this->tokens[$stackPtr]['nested_parenthesis']) === true) { + $brackets = $this->tokens[$stackPtr]['nested_parenthesis']; + $lastBracket = array_pop($brackets); + if (isset($this->tokens[$lastBracket]['parenthesis_owner']) === true) { + $owner = $this->tokens[$this->tokens[$lastBracket]['parenthesis_owner']]; + if ($owner['code'] === T_FUNCTION + || $owner['code'] === T_CLOSURE + || $owner['code'] === T_FN + ) { + $params = $this->getMethodParameters($this->tokens[$lastBracket]['parenthesis_owner']); + foreach ($params as $param) { + if ($param['reference_token'] === $stackPtr) { + // Function parameter declared to be passed by reference. + return true; + } + } + }//end if + } else { + $prev = false; + for ($t = ($this->tokens[$lastBracket]['parenthesis_opener'] - 1); $t >= 0; $t--) { + if ($this->tokens[$t]['code'] !== T_WHITESPACE) { + $prev = $t; + break; + } + } + + if ($prev !== false && $this->tokens[$prev]['code'] === T_USE) { + // Closure use by reference. + return true; + } + }//end if + }//end if + + // Pass by reference in function calls and assign by reference in arrays. + if ($this->tokens[$tokenBefore]['code'] === T_OPEN_PARENTHESIS + || $this->tokens[$tokenBefore]['code'] === T_COMMA + || $this->tokens[$tokenBefore]['code'] === T_OPEN_SHORT_ARRAY + ) { + if ($this->tokens[$tokenAfter]['code'] === T_VARIABLE) { + return true; + } else { + $skip = Util\Tokens::$emptyTokens; + $skip[] = T_NS_SEPARATOR; + $skip[] = T_SELF; + $skip[] = T_PARENT; + $skip[] = T_STATIC; + $skip[] = T_STRING; + $skip[] = T_NAMESPACE; + $skip[] = T_DOUBLE_COLON; + + $nextSignificantAfter = $this->findNext( + $skip, + ($stackPtr + 1), + null, + true + ); + if ($this->tokens[$nextSignificantAfter]['code'] === T_VARIABLE) { + return true; + } + }//end if + }//end if + + return false; + + }//end isReference() + + + /** + * Returns the content of the tokens from the specified start position in + * the token stack for the specified length. + * + * @param int $start The position to start from in the token stack. + * @param int $length The length of tokens to traverse from the start pos. + * @param bool $origContent Whether the original content or the tab replaced + * content should be used. + * + * @return string The token contents. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position does not exist. + */ + public function getTokensAsString($start, $length, $origContent=false) + { + if (is_int($start) === false || isset($this->tokens[$start]) === false) { + throw new RuntimeException('The $start position for getTokensAsString() must exist in the token stack'); + } + + if (is_int($length) === false || $length <= 0) { + return ''; + } + + $str = ''; + $end = ($start + $length); + if ($end > $this->numTokens) { + $end = $this->numTokens; + } + + for ($i = $start; $i < $end; $i++) { + // If tabs are being converted to spaces by the tokeniser, the + // original content should be used instead of the converted content. + if ($origContent === true && isset($this->tokens[$i]['orig_content']) === true) { + $str .= $this->tokens[$i]['orig_content']; + } else { + $str .= $this->tokens[$i]['content']; + } + } + + return $str; + + }//end getTokensAsString() + + + /** + * Returns the position of the previous specified token(s). + * + * If a value is specified, the previous token of the specified type(s) + * containing the specified value will be returned. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. + * @param int|null $end The end position to fail if no token is found. + * if not specified or null, end will default to + * the start of the token stack. + * @param bool $exclude If true, find the previous token that is NOT of + * the types specified in $types. + * @param string|null $value The value that the token(s) must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * @param bool $local If true, tokens outside the current statement + * will not be checked. IE. checking will stop + * at the previous semi-colon found. + * + * @return int|false + * @see findNext() + */ + public function findPrevious( + $types, + $start, + $end=null, + $exclude=false, + $value=null, + $local=false + ) { + $types = (array) $types; + + if ($end === null) { + $end = 0; + } + + for ($i = $start; $i >= $end; $i--) { + $found = (bool) $exclude; + foreach ($types as $type) { + if ($this->tokens[$i]['code'] === $type) { + $found = !$exclude; + break; + } + } + + if ($found === true) { + if ($value === null) { + return $i; + } else if ($this->tokens[$i]['content'] === $value) { + return $i; + } + } + + if ($local === true) { + if (isset($this->tokens[$i]['scope_opener']) === true + && $i === $this->tokens[$i]['scope_closer'] + ) { + $i = $this->tokens[$i]['scope_opener']; + } else if (isset($this->tokens[$i]['bracket_opener']) === true + && $i === $this->tokens[$i]['bracket_closer'] + ) { + $i = $this->tokens[$i]['bracket_opener']; + } else if (isset($this->tokens[$i]['parenthesis_opener']) === true + && $i === $this->tokens[$i]['parenthesis_closer'] + ) { + $i = $this->tokens[$i]['parenthesis_opener']; + } else if ($this->tokens[$i]['code'] === T_SEMICOLON) { + break; + } + } + }//end for + + return false; + + }//end findPrevious() + + + /** + * Returns the position of the next specified token(s). + * + * If a value is specified, the next token of the specified type(s) + * containing the specified value will be returned. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. + * @param int|null $end The end position to fail if no token is found. + * if not specified or null, end will default to + * the end of the token stack. + * @param bool $exclude If true, find the next token that is NOT of + * a type specified in $types. + * @param string|null $value The value that the token(s) must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * @param bool $local If true, tokens outside the current statement + * will not be checked. i.e., checking will stop + * at the next semi-colon found. + * + * @return int|false + * @see findPrevious() + */ + public function findNext( + $types, + $start, + $end=null, + $exclude=false, + $value=null, + $local=false + ) { + $types = (array) $types; + + if ($end === null || $end > $this->numTokens) { + $end = $this->numTokens; + } + + for ($i = $start; $i < $end; $i++) { + $found = (bool) $exclude; + foreach ($types as $type) { + if ($this->tokens[$i]['code'] === $type) { + $found = !$exclude; + break; + } + } + + if ($found === true) { + if ($value === null) { + return $i; + } else if ($this->tokens[$i]['content'] === $value) { + return $i; + } + } + + if ($local === true && $this->tokens[$i]['code'] === T_SEMICOLON) { + break; + } + }//end for + + return false; + + }//end findNext() + + + /** + * Returns the position of the first non-whitespace token in a statement. + * + * @param int $start The position to start searching from in the token stack. + * @param int|string|array $ignore Token types that should not be considered stop points. + * + * @return int + */ + public function findStartOfStatement($start, $ignore=null) + { + $startTokens = Util\Tokens::$blockOpeners; + $startTokens[T_OPEN_SHORT_ARRAY] = true; + $startTokens[T_OPEN_TAG] = true; + $startTokens[T_OPEN_TAG_WITH_ECHO] = true; + + $endTokens = [ + T_CLOSE_TAG => true, + T_COLON => true, + T_COMMA => true, + T_DOUBLE_ARROW => true, + T_MATCH_ARROW => true, + T_SEMICOLON => true, + ]; + + if ($ignore !== null) { + $ignore = (array) $ignore; + foreach ($ignore as $code) { + if (isset($startTokens[$code]) === true) { + unset($startTokens[$code]); + } + + if (isset($endTokens[$code]) === true) { + unset($endTokens[$code]); + } + } + } + + // If the start token is inside the case part of a match expression, + // find the start of the condition. If it's in the statement part, find + // the token that comes after the match arrow. + $matchExpression = $this->getCondition($start, T_MATCH); + if ($matchExpression !== false) { + for ($prevMatch = $start; $prevMatch > $this->tokens[$matchExpression]['scope_opener']; $prevMatch--) { + if ($prevMatch !== $start + && ($this->tokens[$prevMatch]['code'] === T_MATCH_ARROW + || $this->tokens[$prevMatch]['code'] === T_COMMA) + ) { + break; + } + + // Skip nested statements. + if (isset($this->tokens[$prevMatch]['bracket_opener']) === true + && $prevMatch === $this->tokens[$prevMatch]['bracket_closer'] + ) { + $prevMatch = $this->tokens[$prevMatch]['bracket_opener']; + } else if (isset($this->tokens[$prevMatch]['parenthesis_opener']) === true + && $prevMatch === $this->tokens[$prevMatch]['parenthesis_closer'] + ) { + $prevMatch = $this->tokens[$prevMatch]['parenthesis_opener']; + } + } + + if ($prevMatch <= $this->tokens[$matchExpression]['scope_opener']) { + // We're before the arrow in the first case. + $next = $this->findNext(Util\Tokens::$emptyTokens, ($this->tokens[$matchExpression]['scope_opener'] + 1), null, true); + if ($next === false) { + return $start; + } + + return $next; + } + + if ($this->tokens[$prevMatch]['code'] === T_COMMA) { + // We're before the arrow, but not in the first case. + $prevMatchArrow = $this->findPrevious(T_MATCH_ARROW, ($prevMatch - 1), $this->tokens[$matchExpression]['scope_opener']); + if ($prevMatchArrow === false) { + // We're before the arrow in the first case. + $next = $this->findNext(Util\Tokens::$emptyTokens, ($this->tokens[$matchExpression]['scope_opener'] + 1), null, true); + return $next; + } + + $end = $this->findEndOfStatement($prevMatchArrow); + $next = $this->findNext(Util\Tokens::$emptyTokens, ($end + 1), null, true); + return $next; + } + }//end if + + $lastNotEmpty = $start; + + // If we are starting at a token that ends a scope block, skip to + // the start and continue from there. + // If we are starting at a token that ends a statement, skip this + // token so we find the true start of the statement. + while (isset($endTokens[$this->tokens[$start]['code']]) === true + || (isset($this->tokens[$start]['scope_condition']) === true + && $start === $this->tokens[$start]['scope_closer']) + ) { + if (isset($this->tokens[$start]['scope_condition']) === true) { + $start = $this->tokens[$start]['scope_condition']; + } else { + $start--; + } + } + + for ($i = $start; $i >= 0; $i--) { + if (isset($startTokens[$this->tokens[$i]['code']]) === true + || isset($endTokens[$this->tokens[$i]['code']]) === true + ) { + // Found the end of the previous statement. + return $lastNotEmpty; + } + + if (isset($this->tokens[$i]['scope_opener']) === true + && $i === $this->tokens[$i]['scope_closer'] + && $this->tokens[$i]['code'] !== T_CLOSE_PARENTHESIS + && $this->tokens[$i]['code'] !== T_END_NOWDOC + && $this->tokens[$i]['code'] !== T_END_HEREDOC + && $this->tokens[$i]['code'] !== T_BREAK + && $this->tokens[$i]['code'] !== T_RETURN + && $this->tokens[$i]['code'] !== T_CONTINUE + && $this->tokens[$i]['code'] !== T_THROW + && $this->tokens[$i]['code'] !== T_EXIT + ) { + // Found the end of the previous scope block. + return $lastNotEmpty; + } + + // Skip nested statements. + if (isset($this->tokens[$i]['bracket_opener']) === true + && $i === $this->tokens[$i]['bracket_closer'] + ) { + $i = $this->tokens[$i]['bracket_opener']; + } else if (isset($this->tokens[$i]['parenthesis_opener']) === true + && $i === $this->tokens[$i]['parenthesis_closer'] + ) { + $i = $this->tokens[$i]['parenthesis_opener']; + } else if ($this->tokens[$i]['code'] === T_CLOSE_USE_GROUP) { + $start = $this->findPrevious(T_OPEN_USE_GROUP, ($i - 1)); + if ($start !== false) { + $i = $start; + } + }//end if + + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$i]['code']]) === false) { + $lastNotEmpty = $i; + } + }//end for + + return 0; + + }//end findStartOfStatement() + + + /** + * Returns the position of the last non-whitespace token in a statement. + * + * @param int $start The position to start searching from in the token stack. + * @param int|string|array $ignore Token types that should not be considered stop points. + * + * @return int + */ + public function findEndOfStatement($start, $ignore=null) + { + $endTokens = [ + T_COLON => true, + T_COMMA => true, + T_DOUBLE_ARROW => true, + T_SEMICOLON => true, + T_CLOSE_PARENTHESIS => true, + T_CLOSE_SQUARE_BRACKET => true, + T_CLOSE_CURLY_BRACKET => true, + T_CLOSE_SHORT_ARRAY => true, + T_OPEN_TAG => true, + T_CLOSE_TAG => true, + ]; + + if ($ignore !== null) { + $ignore = (array) $ignore; + foreach ($ignore as $code) { + unset($endTokens[$code]); + } + } + + // If the start token is inside the case part of a match expression, + // advance to the match arrow and continue looking for the + // end of the statement from there so that we skip over commas. + if ($this->tokens[$start]['code'] !== T_MATCH_ARROW) { + $matchExpression = $this->getCondition($start, T_MATCH); + if ($matchExpression !== false) { + $beforeArrow = true; + $prevMatchArrow = $this->findPrevious(T_MATCH_ARROW, ($start - 1), $this->tokens[$matchExpression]['scope_opener']); + if ($prevMatchArrow !== false) { + $prevComma = $this->findNext(T_COMMA, ($prevMatchArrow + 1), $start); + if ($prevComma === false) { + // No comma between this token and the last match arrow, + // so this token exists after the arrow and we can continue + // checking as normal. + $beforeArrow = false; + } + } + + if ($beforeArrow === true) { + $nextMatchArrow = $this->findNext(T_MATCH_ARROW, ($start + 1), $this->tokens[$matchExpression]['scope_closer']); + if ($nextMatchArrow !== false) { + $start = $nextMatchArrow; + } + } + }//end if + }//end if + + $lastNotEmpty = $start; + for ($i = $start; $i < $this->numTokens; $i++) { + if ($i !== $start && isset($endTokens[$this->tokens[$i]['code']]) === true) { + // Found the end of the statement. + if ($this->tokens[$i]['code'] === T_CLOSE_PARENTHESIS + || $this->tokens[$i]['code'] === T_CLOSE_SQUARE_BRACKET + || $this->tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET + || $this->tokens[$i]['code'] === T_CLOSE_SHORT_ARRAY + || $this->tokens[$i]['code'] === T_OPEN_TAG + || $this->tokens[$i]['code'] === T_CLOSE_TAG + ) { + return $lastNotEmpty; + } + + return $i; + } + + // Skip nested statements. + if (isset($this->tokens[$i]['scope_closer']) === true + && ($i === $this->tokens[$i]['scope_opener'] + || $i === $this->tokens[$i]['scope_condition']) + ) { + if ($this->tokens[$i]['code'] === T_FN) { + $lastNotEmpty = $this->tokens[$i]['scope_closer']; + $i = ($this->tokens[$i]['scope_closer'] - 1); + continue; + } + + if ($i === $start && isset(Util\Tokens::$scopeOpeners[$this->tokens[$i]['code']]) === true) { + return $this->tokens[$i]['scope_closer']; + } + + $i = $this->tokens[$i]['scope_closer']; + } else if (isset($this->tokens[$i]['bracket_closer']) === true + && $i === $this->tokens[$i]['bracket_opener'] + ) { + $i = $this->tokens[$i]['bracket_closer']; + } else if (isset($this->tokens[$i]['parenthesis_closer']) === true + && $i === $this->tokens[$i]['parenthesis_opener'] + ) { + $i = $this->tokens[$i]['parenthesis_closer']; + } else if ($this->tokens[$i]['code'] === T_OPEN_USE_GROUP) { + $end = $this->findNext(T_CLOSE_USE_GROUP, ($i + 1)); + if ($end !== false) { + $i = $end; + } + }//end if + + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$i]['code']]) === false) { + $lastNotEmpty = $i; + } + }//end for + + return ($this->numTokens - 1); + + }//end findEndOfStatement() + + + /** + * Returns the position of the first token on a line, matching given type. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. + * @param bool $exclude If true, find the token that is NOT of + * the types specified in $types. + * @param string $value The value that the token must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * + * @return int|false The first token which matches on the line containing the start + * token, between the start of the line and the start token. + * Note: The first token matching might be the start token. + * FALSE when no matching token could be found between the start of + * the line and the start token. + */ + public function findFirstOnLine($types, $start, $exclude=false, $value=null) + { + if (is_array($types) === false) { + $types = [$types]; + } + + $foundToken = false; + + for ($i = $start; $i >= 0; $i--) { + if ($this->tokens[$i]['line'] < $this->tokens[$start]['line']) { + break; + } + + $found = $exclude; + foreach ($types as $type) { + if ($exclude === false) { + if ($this->tokens[$i]['code'] === $type) { + $found = true; + break; + } + } else { + if ($this->tokens[$i]['code'] === $type) { + $found = false; + break; + } + } + } + + if ($found === true) { + if ($value === null) { + $foundToken = $i; + } else if ($this->tokens[$i]['content'] === $value) { + $foundToken = $i; + } + } + }//end for + + return $foundToken; + + }//end findFirstOnLine() + + + /** + * Determine if the passed token has a condition of one of the passed types. + * + * @param int $stackPtr The position of the token we are checking. + * @param int|string|array $types The type(s) of tokens to search for. + * + * @return boolean + */ + public function hasCondition($stackPtr, $types) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === false) { + return false; + } + + // Make sure the token has conditions. + if (empty($this->tokens[$stackPtr]['conditions']) === true) { + return false; + } + + $types = (array) $types; + $conditions = $this->tokens[$stackPtr]['conditions']; + + foreach ($types as $type) { + if (in_array($type, $conditions, true) === true) { + // We found a token with the required type. + return true; + } + } + + return false; + + }//end hasCondition() + + + /** + * Return the position of the condition for the passed token. + * + * Returns FALSE if the token does not have the condition. + * + * @param int $stackPtr The position of the token we are checking. + * @param int|string $type The type of token to search for. + * @param bool $first If TRUE, will return the matched condition + * furthest away from the passed token. + * If FALSE, will return the matched condition + * closest to the passed token. + * + * @return int|false + */ + public function getCondition($stackPtr, $type, $first=true) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === false) { + return false; + } + + // Make sure the token has conditions. + if (empty($this->tokens[$stackPtr]['conditions']) === true) { + return false; + } + + $conditions = $this->tokens[$stackPtr]['conditions']; + if ($first === false) { + $conditions = array_reverse($conditions, true); + } + + foreach ($conditions as $token => $condition) { + if ($condition === $type) { + return $token; + } + } + + return false; + + }//end getCondition() + + + /** + * Returns the name of the class that the specified class extends. + * (works for classes, anonymous classes and interfaces) + * + * Returns FALSE on error or if there is no extended class name. + * + * @param int $stackPtr The stack position of the class. + * + * @return string|false + */ + public function findExtendedClassName($stackPtr) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === false) { + return false; + } + + if ($this->tokens[$stackPtr]['code'] !== T_CLASS + && $this->tokens[$stackPtr]['code'] !== T_ANON_CLASS + && $this->tokens[$stackPtr]['code'] !== T_INTERFACE + ) { + return false; + } + + if (isset($this->tokens[$stackPtr]['scope_opener']) === false) { + return false; + } + + $classOpenerIndex = $this->tokens[$stackPtr]['scope_opener']; + $extendsIndex = $this->findNext(T_EXTENDS, $stackPtr, $classOpenerIndex); + if ($extendsIndex === false) { + return false; + } + + $find = [ + T_NS_SEPARATOR, + T_STRING, + T_WHITESPACE, + ]; + + $end = $this->findNext($find, ($extendsIndex + 1), ($classOpenerIndex + 1), true); + $name = $this->getTokensAsString(($extendsIndex + 1), ($end - $extendsIndex - 1)); + $name = trim($name); + + if ($name === '') { + return false; + } + + return $name; + + }//end findExtendedClassName() + + + /** + * Returns the names of the interfaces that the specified class or enum implements. + * + * Returns FALSE on error or if there are no implemented interface names. + * + * @param int $stackPtr The stack position of the class or enum token. + * + * @return array|false + */ + public function findImplementedInterfaceNames($stackPtr) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === false) { + return false; + } + + if ($this->tokens[$stackPtr]['code'] !== T_CLASS + && $this->tokens[$stackPtr]['code'] !== T_ANON_CLASS + && $this->tokens[$stackPtr]['code'] !== T_ENUM + ) { + return false; + } + + if (isset($this->tokens[$stackPtr]['scope_closer']) === false) { + return false; + } + + $classOpenerIndex = $this->tokens[$stackPtr]['scope_opener']; + $implementsIndex = $this->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex); + if ($implementsIndex === false) { + return false; + } + + $find = [ + T_NS_SEPARATOR, + T_STRING, + T_WHITESPACE, + T_COMMA, + ]; + + $end = $this->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true); + $name = $this->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1)); + $name = trim($name); + + if ($name === '') { + return false; + } else { + $names = explode(',', $name); + $names = array_map('trim', $names); + return $names; + } + + }//end findImplementedInterfaceNames() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/FileList.php b/vendor/squizlabs/php_codesniffer/src/Files/FileList.php new file mode 100644 index 0000000..13357ec --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/FileList.php @@ -0,0 +1,255 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Autoload; +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\DeepExitException; +use ReturnTypeWillChange; + +class FileList implements \Iterator, \Countable +{ + + /** + * A list of file paths that are included in the list. + * + * @var array + */ + private $files = []; + + /** + * The number of files in the list. + * + * @var integer + */ + private $numFiles = 0; + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + + /** + * An array of patterns to use for skipping files. + * + * @var array + */ + protected $ignorePatterns = []; + + + /** + * Constructs a file list and loads in an array of file paths to process. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @return void + */ + public function __construct(Config $config, Ruleset $ruleset) + { + $this->ruleset = $ruleset; + $this->config = $config; + + $paths = $config->files; + foreach ($paths as $path) { + $isPharFile = Util\Common::isPharFile($path); + if (is_dir($path) === true || $isPharFile === true) { + if ($isPharFile === true) { + $path = 'phar://'.$path; + } + + $filterClass = $this->getFilterClass(); + + $di = new \RecursiveDirectoryIterator($path, (\RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS)); + $filter = new $filterClass($di, $path, $config, $ruleset); + $iterator = new \RecursiveIteratorIterator($filter); + + foreach ($iterator as $file) { + $this->files[$file->getPathname()] = null; + $this->numFiles++; + } + } else { + $this->addFile($path); + }//end if + }//end foreach + + reset($this->files); + + }//end __construct() + + + /** + * Add a file to the list. + * + * If a file object has already been created, it can be passed here. + * If it is left NULL, it will be created when accessed. + * + * @param string $path The path to the file being added. + * @param \PHP_CodeSniffer\Files\File $file The file being added. + * + * @return void + */ + public function addFile($path, $file=null) + { + // No filtering is done for STDIN when the filename + // has not been specified. + if ($path === 'STDIN') { + $this->files[$path] = $file; + $this->numFiles++; + return; + } + + $filterClass = $this->getFilterClass(); + + $di = new \RecursiveArrayIterator([$path]); + $filter = new $filterClass($di, $path, $this->config, $this->ruleset); + $iterator = new \RecursiveIteratorIterator($filter); + + foreach ($iterator as $path) { + $this->files[$path] = $file; + $this->numFiles++; + } + + }//end addFile() + + + /** + * Get the class name of the filter being used for the run. + * + * @return string + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the specified filter could not be found. + */ + private function getFilterClass() + { + $filterType = $this->config->filter; + + if ($filterType === null) { + $filterClass = '\PHP_CodeSniffer\Filters\Filter'; + } else { + if (strpos($filterType, '.') !== false) { + // This is a path to a custom filter class. + $filename = realpath($filterType); + if ($filename === false) { + $error = "ERROR: Custom filter \"$filterType\" not found".PHP_EOL; + throw new DeepExitException($error, 3); + } + + $filterClass = Autoload::loadFile($filename); + } else { + $filterClass = '\PHP_CodeSniffer\Filters\\'.$filterType; + } + } + + return $filterClass; + + }//end getFilterClass() + + + /** + * Rewind the iterator to the first file. + * + * @return void + */ + #[ReturnTypeWillChange] + public function rewind() + { + reset($this->files); + + }//end rewind() + + + /** + * Get the file that is currently being processed. + * + * @return \PHP_CodeSniffer\Files\File + */ + #[ReturnTypeWillChange] + public function current() + { + $path = key($this->files); + if (isset($this->files[$path]) === false) { + $this->files[$path] = new LocalFile($path, $this->ruleset, $this->config); + } + + return $this->files[$path]; + + }//end current() + + + /** + * Return the file path of the current file being processed. + * + * @return string|null Path name or `null` when the end of the iterator has been reached. + */ + #[ReturnTypeWillChange] + public function key() + { + return key($this->files); + + }//end key() + + + /** + * Move forward to the next file. + * + * @return void + */ + #[ReturnTypeWillChange] + public function next() + { + next($this->files); + + }//end next() + + + /** + * Checks if current position is valid. + * + * @return boolean + */ + #[ReturnTypeWillChange] + public function valid() + { + if (current($this->files) === false) { + return false; + } + + return true; + + }//end valid() + + + /** + * Return the number of files in the list. + * + * @return integer + */ + #[ReturnTypeWillChange] + public function count() + { + return $this->numFiles; + + }//end count() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php b/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php new file mode 100644 index 0000000..c2af77c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php @@ -0,0 +1,219 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Util\Cache; +use PHP_CodeSniffer\Util\Common; + +class LocalFile extends File +{ + + + /** + * Creates a LocalFile object and sets the content. + * + * @param string $path The absolute path to the file. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($path, Ruleset $ruleset, Config $config) + { + $this->path = trim($path); + if (Common::isReadable($this->path) === false) { + parent::__construct($this->path, $ruleset, $config); + $error = 'Error opening file; file no longer exists or you do not have access to read the file'; + $this->addMessage(true, $error, 1, 1, 'Internal.LocalFile', [], 5, false); + $this->ignored = true; + return; + } + + // Before we go and spend time tokenizing this file, just check + // to see if there is a tag up top to indicate that the whole + // file should be ignored. It must be on one of the first two lines. + if ($config->annotations === true) { + $handle = fopen($this->path, 'r'); + if ($handle !== false) { + $firstContent = fgets($handle); + $firstContent .= fgets($handle); + fclose($handle); + + if (strpos($firstContent, '@codingStandardsIgnoreFile') !== false + || stripos($firstContent, 'phpcs:ignorefile') !== false + ) { + // We are ignoring the whole file. + $this->ignored = true; + return; + } + } + } + + $this->reloadContent(); + + parent::__construct($this->path, $ruleset, $config); + + }//end __construct() + + + /** + * Loads the latest version of the file's content from the file system. + * + * @return void + */ + public function reloadContent() + { + $this->setContent(file_get_contents($this->path)); + + }//end reloadContent() + + + /** + * Processes the file. + * + * @return void + */ + public function process() + { + if ($this->ignored === true) { + return; + } + + if ($this->configCache['cache'] === false) { + parent::process(); + return; + } + + $hash = md5_file($this->path); + $hash .= fileperms($this->path); + $cache = Cache::get($this->path); + if ($cache !== false && $cache['hash'] === $hash) { + // We can't filter metrics, so just load all of them. + $this->metrics = $cache['metrics']; + + if ($this->configCache['recordErrors'] === true) { + // Replay the cached errors and warnings to filter out the ones + // we don't need for this specific run. + $this->configCache['cache'] = false; + $this->replayErrors($cache['errors'], $cache['warnings']); + $this->configCache['cache'] = true; + } else { + $this->errorCount = $cache['errorCount']; + $this->warningCount = $cache['warningCount']; + $this->fixableCount = $cache['fixableCount']; + } + + if (PHP_CODESNIFFER_VERBOSITY > 0 + || (PHP_CODESNIFFER_CBF === true && empty($this->config->files) === false) + ) { + echo "[loaded from cache]... "; + } + + $this->numTokens = $cache['numTokens']; + $this->fromCache = true; + return; + }//end if + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + + parent::process(); + + $cache = [ + 'hash' => $hash, + 'errors' => $this->errors, + 'warnings' => $this->warnings, + 'metrics' => $this->metrics, + 'errorCount' => $this->errorCount, + 'warningCount' => $this->warningCount, + 'fixableCount' => $this->fixableCount, + 'numTokens' => $this->numTokens, + ]; + + Cache::set($this->path, $cache); + + // During caching, we don't filter out errors in any way, so + // we need to do that manually now by replaying them. + if ($this->configCache['recordErrors'] === true) { + $this->configCache['cache'] = false; + $this->replayErrors($this->errors, $this->warnings); + $this->configCache['cache'] = true; + } + + }//end process() + + + /** + * Clears and replays error and warnings for the file. + * + * Replaying errors and warnings allows for filtering rules to be changed + * and then errors and warnings to be reapplied with the new rules. This is + * particularly useful while caching. + * + * @param array $errors The list of errors to replay. + * @param array $warnings The list of warnings to replay. + * + * @return void + */ + private function replayErrors($errors, $warnings) + { + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + + $this->replayingErrors = true; + + foreach ($errors as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $this->activeListener = $error['listener']; + $this->addMessage( + true, + $error['message'], + $line, + $column, + $error['source'], + [], + $error['severity'], + $error['fixable'] + ); + } + } + } + + foreach ($warnings as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $this->activeListener = $error['listener']; + $this->addMessage( + false, + $error['message'], + $line, + $column, + $error['source'], + [], + $error['severity'], + $error['fixable'] + ); + } + } + } + + $this->replayingErrors = false; + + }//end replayErrors() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php b/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php new file mode 100644 index 0000000..ce04e02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php @@ -0,0 +1,108 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; + +abstract class ExactMatch extends Filter +{ + + /** + * A list of files to exclude. + * + * @var array + */ + private $blockedFiles = null; + + /** + * A list of files to include. + * + * If the allowed files list is empty, only files in the blocked files list will be excluded. + * + * @var array + */ + private $allowedFiles = null; + + + /** + * Check whether the current element of the iterator is acceptable. + * + * If a file is both blocked and allowed, it will be deemed unacceptable. + * + * @return bool + */ + public function accept() + { + if (parent::accept() === false) { + return false; + } + + if ($this->blockedFiles === null) { + $this->blockedFiles = $this->getblacklist(); + } + + if ($this->allowedFiles === null) { + $this->allowedFiles = $this->getwhitelist(); + } + + $filePath = Util\Common::realpath($this->current()); + + // If file is both blocked and allowed, the blocked files list takes precedence. + if (isset($this->blockedFiles[$filePath]) === true) { + return false; + } + + if (empty($this->allowedFiles) === true && empty($this->blockedFiles) === false) { + // We are only checking a blocked files list, so everything else should be allowed. + return true; + } + + return isset($this->allowedFiles[$filePath]); + + }//end accept() + + + /** + * Returns an iterator for the current entry. + * + * Ensures that the blocked files list and the allowed files list are preserved so they don't have + * to be generated each time. + * + * @return \RecursiveIterator + */ + public function getChildren() + { + $children = parent::getChildren(); + $children->blockedFiles = $this->blockedFiles; + $children->allowedFiles = $this->allowedFiles; + return $children; + + }//end getChildren() + + + /** + * Get a list of file paths to exclude. + * + * @return array + */ + abstract protected function getBlacklist(); + + + /** + * Get a list of file paths to include. + * + * @return array + */ + abstract protected function getWhitelist(); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php b/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php new file mode 100644 index 0000000..c72518c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php @@ -0,0 +1,285 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use ReturnTypeWillChange; + +class Filter extends \RecursiveFilterIterator +{ + + /** + * The top-level path we are filtering. + * + * @var string + */ + protected $basedir = null; + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + protected $config = null; + + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected $ruleset = null; + + /** + * A list of ignore patterns that apply to directories only. + * + * @var array + */ + protected $ignoreDirPatterns = null; + + /** + * A list of ignore patterns that apply to files only. + * + * @var array + */ + protected $ignoreFilePatterns = null; + + /** + * A list of file paths we've already accepted. + * + * Used to ensure we aren't following circular symlinks. + * + * @var array + */ + protected $acceptedPaths = []; + + + /** + * Constructs a filter. + * + * @param \RecursiveIterator $iterator The iterator we are using to get file paths. + * @param string $basedir The top-level path we are filtering. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @return void + */ + public function __construct($iterator, $basedir, Config $config, Ruleset $ruleset) + { + parent::__construct($iterator); + $this->basedir = $basedir; + $this->config = $config; + $this->ruleset = $ruleset; + + }//end __construct() + + + /** + * Check whether the current element of the iterator is acceptable. + * + * Files are checked for allowed extensions and ignore patterns. + * Directories are checked for ignore patterns only. + * + * @return bool + */ + #[ReturnTypeWillChange] + public function accept() + { + $filePath = $this->current(); + $realPath = Util\Common::realpath($filePath); + + if ($realPath !== false) { + // It's a real path somewhere, so record it + // to check for circular symlinks. + if (isset($this->acceptedPaths[$realPath]) === true) { + // We've been here before. + return false; + } + } + + $filePath = $this->current(); + if (is_dir($filePath) === true) { + if ($this->config->local === true) { + return false; + } + } else if ($this->shouldProcessFile($filePath) === false) { + return false; + } + + if ($this->shouldIgnorePath($filePath) === true) { + return false; + } + + $this->acceptedPaths[$realPath] = true; + return true; + + }//end accept() + + + /** + * Returns an iterator for the current entry. + * + * Ensures that the ignore patterns are preserved so they don't have + * to be generated each time. + * + * @return \RecursiveIterator + */ + #[ReturnTypeWillChange] + public function getChildren() + { + $filterClass = get_called_class(); + $children = new $filterClass( + new \RecursiveDirectoryIterator($this->current(), (\RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS)), + $this->basedir, + $this->config, + $this->ruleset + ); + + // Set the ignore patterns so we don't have to generate them again. + $children->ignoreDirPatterns = $this->ignoreDirPatterns; + $children->ignoreFilePatterns = $this->ignoreFilePatterns; + $children->acceptedPaths = $this->acceptedPaths; + return $children; + + }//end getChildren() + + + /** + * Checks filtering rules to see if a file should be checked. + * + * Checks both file extension filters and path ignore filters. + * + * @param string $path The path to the file being checked. + * + * @return bool + */ + protected function shouldProcessFile($path) + { + // Check that the file's extension is one we are checking. + // We are strict about checking the extension and we don't + // let files through with no extension or that start with a dot. + $fileName = basename($path); + $fileParts = explode('.', $fileName); + if ($fileParts[0] === $fileName || $fileParts[0] === '') { + return false; + } + + // Checking multi-part file extensions, so need to create a + // complete extension list and make sure one is allowed. + $extensions = []; + array_shift($fileParts); + foreach ($fileParts as $part) { + $extensions[implode('.', $fileParts)] = 1; + array_shift($fileParts); + } + + $matches = array_intersect_key($extensions, $this->config->extensions); + if (empty($matches) === true) { + return false; + } + + return true; + + }//end shouldProcessFile() + + + /** + * Checks filtering rules to see if a path should be ignored. + * + * @param string $path The path to the file or directory being checked. + * + * @return bool + */ + protected function shouldIgnorePath($path) + { + if ($this->ignoreFilePatterns === null) { + $this->ignoreDirPatterns = []; + $this->ignoreFilePatterns = []; + + $ignorePatterns = $this->config->ignored; + $rulesetIgnorePatterns = $this->ruleset->getIgnorePatterns(); + foreach ($rulesetIgnorePatterns as $pattern => $type) { + // Ignore standard/sniff specific exclude rules. + if (is_array($type) === true) { + continue; + } + + $ignorePatterns[$pattern] = $type; + } + + foreach ($ignorePatterns as $pattern => $type) { + // If the ignore pattern ends with /* then it is ignoring an entire directory. + if (substr($pattern, -2) === '/*') { + // Need to check this pattern for dirs as well as individual file paths. + $this->ignoreFilePatterns[$pattern] = $type; + + $pattern = substr($pattern, 0, -2).'(?=/|$)'; + $this->ignoreDirPatterns[$pattern] = $type; + } else { + // This is a file-specific pattern, so only need to check this + // for individual file paths. + $this->ignoreFilePatterns[$pattern] = $type; + } + } + }//end if + + $relativePath = $path; + if (strpos($path, $this->basedir) === 0) { + // The +1 cuts off the directory separator as well. + $relativePath = substr($path, (strlen($this->basedir) + 1)); + } + + if (is_dir($path) === true) { + $ignorePatterns = $this->ignoreDirPatterns; + } else { + $ignorePatterns = $this->ignoreFilePatterns; + } + + foreach ($ignorePatterns as $pattern => $type) { + // Maintains backwards compatibility in case the ignore pattern does + // not have a relative/absolute value. + if (is_int($pattern) === true) { + $pattern = $type; + $type = 'absolute'; + } + + $replacements = [ + '\\,' => ',', + '*' => '.*', + ]; + + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (DIRECTORY_SEPARATOR === '\\') { + $replacements['/'] = '\\\\'; + } + + $pattern = strtr($pattern, $replacements); + + if ($type === 'relative') { + $testPath = $relativePath; + } else { + $testPath = $path; + } + + $pattern = '`'.$pattern.'`i'; + if (preg_match($pattern, $testPath) === 1) { + return true; + } + }//end foreach + + return false; + + }//end shouldIgnorePath() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php b/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php new file mode 100644 index 0000000..3395e06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php @@ -0,0 +1,88 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; + +class GitModified extends ExactMatch +{ + + + /** + * Get a list of file paths to exclude. + * + * @return array + */ + protected function getBlacklist() + { + return []; + + }//end getBlacklist() + + + /** + * Get a list of file paths to include. + * + * @return array + */ + protected function getWhitelist() + { + $modified = []; + + $cmd = 'git ls-files -o -m --exclude-standard -- '.escapeshellarg($this->basedir); + $output = $this->exec($cmd); + + $basedir = $this->basedir; + if (is_dir($basedir) === false) { + $basedir = dirname($basedir); + } + + foreach ($output as $path) { + $path = Util\Common::realpath($path); + + if ($path === false) { + continue; + } + + do { + $modified[$path] = true; + $path = dirname($path); + } while ($path !== $basedir); + } + + return $modified; + + }//end getWhitelist() + + + /** + * Execute an external command. + * + * {@internal This method is only needed to allow for mocking the return value + * to test the class logic.} + * + * @param string $cmd Command. + * + * @return array + */ + protected function exec($cmd) + { + $output = []; + $lastLine = exec($cmd, $output); + if ($lastLine === false) { + return []; + } + + return $output; + + }//end exec() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php b/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php new file mode 100644 index 0000000..94c9194 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php @@ -0,0 +1,90 @@ + + * @copyright 2018 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; + +class GitStaged extends ExactMatch +{ + + + /** + * Get a list of file paths to exclude. + * + * @return array + */ + protected function getBlacklist() + { + return []; + + }//end getBlacklist() + + + /** + * Get a list of file paths to include. + * + * @return array + */ + protected function getWhitelist() + { + $modified = []; + + $cmd = 'git diff --cached --name-only -- '.escapeshellarg($this->basedir); + $output = $this->exec($cmd); + + $basedir = $this->basedir; + if (is_dir($basedir) === false) { + $basedir = dirname($basedir); + } + + foreach ($output as $path) { + $path = Util\Common::realpath($path); + if ($path === false) { + // Skip deleted files. + continue; + } + + do { + $modified[$path] = true; + $path = dirname($path); + } while ($path !== $basedir); + } + + return $modified; + + }//end getWhitelist() + + + /** + * Execute an external command. + * + * {@internal This method is only needed to allow for mocking the return value + * to test the class logic.} + * + * @param string $cmd Command. + * + * @return array + */ + protected function exec($cmd) + { + $output = []; + $lastLine = exec($cmd, $output); + if ($lastLine === false) { + return []; + } + + return $output; + + }//end exec() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Fixer.php b/vendor/squizlabs/php_codesniffer/src/Fixer.php new file mode 100644 index 0000000..b54dde9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Fixer.php @@ -0,0 +1,806 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Common; + +class Fixer +{ + + /** + * Is the fixer enabled and fixing a file? + * + * Sniffs should check this value to ensure they are not + * doing extra processing to prepare for a fix when fixing is + * not required. + * + * @var boolean + */ + public $enabled = false; + + /** + * The number of times we have looped over a file. + * + * @var integer + */ + public $loops = 0; + + /** + * The file being fixed. + * + * @var \PHP_CodeSniffer\Files\File + */ + private $currentFile = null; + + /** + * The list of tokens that make up the file contents. + * + * This is a simplified list which just contains the token content and nothing + * else. This is the array that is updated as fixes are made, not the file's + * token array. Imploding this array will give you the file content back. + * + * @var array + */ + private $tokens = []; + + /** + * A list of tokens that have already been fixed. + * + * We don't allow the same token to be fixed more than once each time + * through a file as this can easily cause conflicts between sniffs. + * + * @var int[] + */ + private $fixedTokens = []; + + /** + * The last value of each fixed token. + * + * If a token is being "fixed" back to its last value, the fix is + * probably conflicting with another. + * + * @var array> + */ + private $oldTokenValues = []; + + /** + * A list of tokens that have been fixed during a changeset. + * + * All changes in changeset must be able to be applied, or else + * the entire changeset is rejected. + * + * @var array + */ + private $changeset = []; + + /** + * Is there an open changeset. + * + * @var boolean + */ + private $inChangeset = false; + + /** + * Is the current fixing loop in conflict? + * + * @var boolean + */ + private $inConflict = false; + + /** + * The number of fixes that have been performed. + * + * @var integer + */ + private $numFixes = 0; + + + /** + * Starts fixing a new file. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being fixed. + * + * @return void + */ + public function startFile(File $phpcsFile) + { + $this->currentFile = $phpcsFile; + $this->numFixes = 0; + $this->fixedTokens = []; + + $tokens = $phpcsFile->getTokens(); + $this->tokens = []; + foreach ($tokens as $index => $token) { + if (isset($token['orig_content']) === true) { + $this->tokens[$index] = $token['orig_content']; + } else { + $this->tokens[$index] = $token['content']; + } + } + + }//end startFile() + + + /** + * Attempt to fix the file by processing it until no fixes are made. + * + * @return boolean + */ + public function fixFile() + { + $fixable = $this->currentFile->getFixableCount(); + if ($fixable === 0) { + // Nothing to fix. + return false; + } + + $this->enabled = true; + + $this->loops = 0; + while ($this->loops < 50) { + ob_start(); + + // Only needed once file content has changed. + $contents = $this->getContents(); + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + @ob_end_clean(); + echo '---START FILE CONTENT---'.PHP_EOL; + $lines = explode($this->currentFile->eolChar, $contents); + $max = strlen(count($lines)); + foreach ($lines as $lineNum => $line) { + $lineNum++; + echo str_pad($lineNum, $max, ' ', STR_PAD_LEFT).'|'.$line.PHP_EOL; + } + + echo '--- END FILE CONTENT ---'.PHP_EOL; + ob_start(); + } + + $this->inConflict = false; + $this->currentFile->ruleset->populateTokenListeners(); + $this->currentFile->setContent($contents); + $this->currentFile->process(); + ob_end_clean(); + + $this->loops++; + + if (PHP_CODESNIFFER_CBF === true && PHP_CODESNIFFER_VERBOSITY > 0) { + echo "\r".str_repeat(' ', 80)."\r"; + echo "\t=> Fixing file: $this->numFixes/$fixable violations remaining [made $this->loops pass"; + if ($this->loops > 1) { + echo 'es'; + } + + echo ']... '; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + } + + if ($this->numFixes === 0 && $this->inConflict === false) { + // Nothing left to do. + break; + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* fixed $this->numFixes violations, starting loop ".($this->loops + 1).' *'.PHP_EOL; + } + }//end while + + $this->enabled = false; + + if ($this->numFixes > 0) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if (ob_get_level() > 0) { + ob_end_clean(); + } + + echo "\t*** Reached maximum number of loops with $this->numFixes violations left unfixed ***".PHP_EOL; + ob_start(); + } + + return false; + } + + return true; + + }//end fixFile() + + + /** + * Generates a text diff of the original file and the new content. + * + * @param string $filePath Optional file path to diff the file against. + * If not specified, the original version of the + * file will be used. + * @param boolean $colors Print coloured output or not. + * + * @return string + */ + public function generateDiff($filePath=null, $colors=true) + { + if ($filePath === null) { + $filePath = $this->currentFile->getFilename(); + } + + $cwd = getcwd().DIRECTORY_SEPARATOR; + if (strpos($filePath, $cwd) === 0) { + $filename = substr($filePath, strlen($cwd)); + } else { + $filename = $filePath; + } + + $contents = $this->getContents(); + + $tempName = tempnam(sys_get_temp_dir(), 'phpcs-fixer'); + $fixedFile = fopen($tempName, 'w'); + fwrite($fixedFile, $contents); + + // We must use something like shell_exec() because whitespace at the end + // of lines is critical to diff files. + $filename = escapeshellarg($filename); + $cmd = "diff -u -L$filename -LPHP_CodeSniffer $filename \"$tempName\""; + + $diff = shell_exec($cmd); + + fclose($fixedFile); + if (is_file($tempName) === true) { + unlink($tempName); + } + + if ($diff === null) { + return ''; + } + + if ($colors === false) { + return $diff; + } + + $diffLines = explode(PHP_EOL, $diff); + if (count($diffLines) === 1) { + // Seems to be required for cygwin. + $diffLines = explode("\n", $diff); + } + + $diff = []; + foreach ($diffLines as $line) { + if (isset($line[0]) === true) { + switch ($line[0]) { + case '-': + $diff[] = "\033[31m$line\033[0m"; + break; + case '+': + $diff[] = "\033[32m$line\033[0m"; + break; + default: + $diff[] = $line; + } + } + } + + $diff = implode(PHP_EOL, $diff); + + return $diff; + + }//end generateDiff() + + + /** + * Get a count of fixes that have been performed on the file. + * + * This value is reset every time a new file is started, or an existing + * file is restarted. + * + * @return int + */ + public function getFixCount() + { + return $this->numFixes; + + }//end getFixCount() + + + /** + * Get the current content of the file, as a string. + * + * @return string + */ + public function getContents() + { + $contents = implode($this->tokens); + return $contents; + + }//end getContents() + + + /** + * Get the current fixed content of a token. + * + * This function takes changesets into account so should be used + * instead of directly accessing the token array. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return string + */ + public function getTokenContent($stackPtr) + { + if ($this->inChangeset === true + && isset($this->changeset[$stackPtr]) === true + ) { + return $this->changeset[$stackPtr]; + } else { + return $this->tokens[$stackPtr]; + } + + }//end getTokenContent() + + + /** + * Start recording actions for a changeset. + * + * @return void|false + */ + public function beginChangeset() + { + if ($this->inConflict === true) { + return false; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === __CLASS__) { + $sniff = 'Fixer'; + } else { + $sniff = Util\Common::getSniffCode($bt[1]['class']); + } + + $line = $bt[0]['line']; + + @ob_end_clean(); + echo "\t=> Changeset started by $sniff:$line".PHP_EOL; + ob_start(); + } + + $this->changeset = []; + $this->inChangeset = true; + + }//end beginChangeset() + + + /** + * Stop recording actions for a changeset, and apply logged changes. + * + * @return boolean + */ + public function endChangeset() + { + if ($this->inConflict === true) { + return false; + } + + $this->inChangeset = false; + + $success = true; + $applied = []; + foreach ($this->changeset as $stackPtr => $content) { + $success = $this->replaceToken($stackPtr, $content); + if ($success === false) { + break; + } else { + $applied[] = $stackPtr; + } + } + + if ($success === false) { + // Rolling back all changes. + foreach ($applied as $stackPtr) { + $this->revertToken($stackPtr); + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + @ob_end_clean(); + echo "\t=> Changeset failed to apply".PHP_EOL; + ob_start(); + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + $fixes = count($this->changeset); + @ob_end_clean(); + echo "\t=> Changeset ended: $fixes changes applied".PHP_EOL; + ob_start(); + } + + $this->changeset = []; + return true; + + }//end endChangeset() + + + /** + * Stop recording actions for a changeset, and discard logged changes. + * + * @return void + */ + public function rollbackChangeset() + { + $this->inChangeset = false; + $this->inConflict = false; + + if (empty($this->changeset) === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = debug_backtrace(); + if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + + $sniff = Util\Common::getSniffCode($sniff); + + $numChanges = count($this->changeset); + + @ob_end_clean(); + echo "\t\tR: $sniff:$line rolled back the changeset ($numChanges changes)".PHP_EOL; + echo "\t=> Changeset rolled back".PHP_EOL; + ob_start(); + } + + $this->changeset = []; + }//end if + + }//end rollbackChangeset() + + + /** + * Replace the entire contents of a token. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The new content of the token. + * + * @return bool If the change was accepted. + */ + public function replaceToken($stackPtr, $content) + { + if ($this->inConflict === true) { + return false; + } + + if ($this->inChangeset === false + && isset($this->fixedTokens[$stackPtr]) === true + ) { + $indent = "\t"; + if (empty($this->changeset) === false) { + $indent .= "\t"; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + @ob_end_clean(); + echo "$indent* token $stackPtr has already been modified, skipping *".PHP_EOL; + ob_start(); + } + + return false; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + + $sniff = Util\Common::getSniffCode($sniff); + + $tokens = $this->currentFile->getTokens(); + $type = $tokens[$stackPtr]['type']; + $tokenLine = $tokens[$stackPtr]['line']; + $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]); + $newContent = Common::prepareForOutput($content); + if (trim($this->tokens[$stackPtr]) === '' && isset($this->tokens[($stackPtr + 1)]) === true) { + // Add some context for whitespace only changes. + $append = Common::prepareForOutput($this->tokens[($stackPtr + 1)]); + $oldContent .= $append; + $newContent .= $append; + } + }//end if + + if ($this->inChangeset === true) { + $this->changeset[$stackPtr] = $content; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + @ob_end_clean(); + echo "\t\tQ: $sniff:$line replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL; + ob_start(); + } + + return true; + } + + if (isset($this->oldTokenValues[$stackPtr]) === false) { + $this->oldTokenValues[$stackPtr] = [ + 'curr' => $content, + 'prev' => $this->tokens[$stackPtr], + 'loop' => $this->loops, + ]; + } else { + if ($this->oldTokenValues[$stackPtr]['prev'] === $content + && $this->oldTokenValues[$stackPtr]['loop'] === ($this->loops - 1) + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === false) { + $indent .= "\t"; + } + + $loop = $this->oldTokenValues[$stackPtr]['loop']; + + @ob_end_clean(); + echo "$indent**** $sniff:$line has possible conflict with another sniff on loop $loop; caused by the following change ****".PHP_EOL; + echo "$indent**** replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\" ****".PHP_EOL; + } + + if ($this->oldTokenValues[$stackPtr]['loop'] >= ($this->loops - 1)) { + $this->inConflict = true; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "$indent**** ignoring all changes until next loop ****".PHP_EOL; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + ob_start(); + } + + return false; + }//end if + + $this->oldTokenValues[$stackPtr]['prev'] = $this->oldTokenValues[$stackPtr]['curr']; + $this->oldTokenValues[$stackPtr]['curr'] = $content; + $this->oldTokenValues[$stackPtr]['loop'] = $this->loops; + }//end if + + $this->fixedTokens[$stackPtr] = $this->tokens[$stackPtr]; + $this->tokens[$stackPtr] = $content; + $this->numFixes++; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === false) { + $indent .= "\tA: "; + } + + if (ob_get_level() > 0) { + ob_end_clean(); + } + + echo "$indent$sniff:$line replaced token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL; + ob_start(); + } + + return true; + + }//end replaceToken() + + + /** + * Reverts the previous fix made to a token. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If a change was reverted. + */ + public function revertToken($stackPtr) + { + if (isset($this->fixedTokens[$stackPtr]) === false) { + return false; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === 'PHP_CodeSniffer\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + + $sniff = Util\Common::getSniffCode($sniff); + + $tokens = $this->currentFile->getTokens(); + $type = $tokens[$stackPtr]['type']; + $tokenLine = $tokens[$stackPtr]['line']; + $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]); + $newContent = Common::prepareForOutput($this->fixedTokens[$stackPtr]); + if (trim($this->tokens[$stackPtr]) === '' && isset($tokens[($stackPtr + 1)]) === true) { + // Add some context for whitespace only changes. + $append = Common::prepareForOutput($this->tokens[($stackPtr + 1)]); + $oldContent .= $append; + $newContent .= $append; + } + }//end if + + $this->tokens[$stackPtr] = $this->fixedTokens[$stackPtr]; + unset($this->fixedTokens[$stackPtr]); + $this->numFixes--; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === false) { + $indent .= "\tR: "; + } + + @ob_end_clean(); + echo "$indent$sniff:$line reverted token $stackPtr ($type on line $tokenLine) \"$oldContent\" => \"$newContent\"".PHP_EOL; + ob_start(); + } + + return true; + + }//end revertToken() + + + /** + * Replace the content of a token with a part of its current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param int $start The first character to keep. + * @param int $length The number of characters to keep. If NULL, the content of + * the token from $start to the end of the content is kept. + * + * @return bool If the change was accepted. + */ + public function substrToken($stackPtr, $start, $length=null) + { + $current = $this->getTokenContent($stackPtr); + + if ($length === null) { + $newContent = substr($current, $start); + } else { + $newContent = substr($current, $start, $length); + } + + return $this->replaceToken($stackPtr, $newContent); + + }//end substrToken() + + + /** + * Adds a newline to end of a token's content. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If the change was accepted. + */ + public function addNewline($stackPtr) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $current.$this->currentFile->eolChar); + + }//end addNewline() + + + /** + * Adds a newline to the start of a token's content. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If the change was accepted. + */ + public function addNewlineBefore($stackPtr) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $this->currentFile->eolChar.$current); + + }//end addNewlineBefore() + + + /** + * Adds content to the end of a token's current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The content to add. + * + * @return bool If the change was accepted. + */ + public function addContent($stackPtr, $content) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $current.$content); + + }//end addContent() + + + /** + * Adds content to the start of a token's current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The content to add. + * + * @return bool If the change was accepted. + */ + public function addContentBefore($stackPtr, $content) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $content.$current); + + }//end addContentBefore() + + + /** + * Adjust the indent of a code block. + * + * @param int $start The position of the token in the token stack + * to start adjusting the indent from. + * @param int $end The position of the token in the token stack + * to end adjusting the indent. + * @param int $change The number of spaces to adjust the indent by + * (positive or negative). + * + * @return void + */ + public function changeCodeBlockIndent($start, $end, $change) + { + $tokens = $this->currentFile->getTokens(); + + $baseIndent = ''; + if ($change > 0) { + $baseIndent = str_repeat(' ', $change); + } + + $useChangeset = false; + if ($this->inChangeset === false) { + $this->beginChangeset(); + $useChangeset = true; + } + + for ($i = $start; $i <= $end; $i++) { + if ($tokens[$i]['column'] !== 1 + || $tokens[($i + 1)]['line'] !== $tokens[$i]['line'] + ) { + continue; + } + + $length = 0; + if ($tokens[$i]['code'] === T_WHITESPACE + || $tokens[$i]['code'] === T_DOC_COMMENT_WHITESPACE + ) { + $length = $tokens[$i]['length']; + + $padding = ($length + $change); + if ($padding > 0) { + $padding = str_repeat(' ', $padding); + } else { + $padding = ''; + } + + $newContent = $padding.ltrim($tokens[$i]['content']); + } else { + $newContent = $baseIndent.$tokens[$i]['content']; + } + + $this->replaceToken($i, $newContent); + }//end for + + if ($useChangeset === true) { + $this->endChangeset(); + } + + }//end changeCodeBlockIndent() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php b/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php new file mode 100644 index 0000000..483cae8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php @@ -0,0 +1,117 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Autoload; + +abstract class Generator +{ + + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + + /** + * XML documentation files used to produce the final output. + * + * @var string[] + */ + public $docFiles = []; + + + /** + * Constructs a doc generator. + * + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @see generate() + */ + public function __construct(Ruleset $ruleset) + { + $this->ruleset = $ruleset; + + foreach ($ruleset->sniffs as $className => $sniffClass) { + $file = Autoload::getLoadedFileName($className); + $docFile = str_replace( + DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR.'Docs'.DIRECTORY_SEPARATOR, + $file + ); + $docFile = str_replace('Sniff.php', 'Standard.xml', $docFile); + + if (is_file($docFile) === true) { + $this->docFiles[] = $docFile; + } + } + + }//end __construct() + + + /** + * Retrieves the title of the sniff from the DOMNode supplied. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return string + */ + protected function getTitle(\DOMNode $doc) + { + return $doc->getAttribute('title'); + + }//end getTitle() + + + /** + * Generates the documentation for a standard. + * + * It's probably wise for doc generators to override this method so they + * have control over how the docs are produced. Otherwise, the processSniff + * method should be overridden to output content for each sniff. + * + * @return void + * @see processSniff() + */ + public function generate() + { + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + + }//end generate() + + + /** + * Process the documentation for a single sniff. + * + * Doc generators must implement this function to produce output. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + * @see generate() + */ + abstract protected function processSniff(\DOMNode $doc); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php b/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php new file mode 100644 index 0000000..55acd9e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php @@ -0,0 +1,270 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Config; + +class HTML extends Generator +{ + + + /** + * Generates the documentation for a standard. + * + * @return void + * @see processSniff() + */ + public function generate() + { + ob_start(); + $this->printHeader(); + $this->printToc(); + + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + + $this->printFooter(); + + $content = ob_get_contents(); + ob_end_clean(); + + echo $content; + + }//end generate() + + + /** + * Print the header of the HTML page. + * + * @return void + */ + protected function printHeader() + { + $standard = $this->ruleset->name; + echo ''.PHP_EOL; + echo ' '.PHP_EOL; + echo " $standard Coding Standards".PHP_EOL; + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo "

$standard Coding Standards

".PHP_EOL; + + }//end printHeader() + + + /** + * Print the table of contents for the standard. + * + * The TOC is just an unordered list of bookmarks to sniffs on the page. + * + * @return void + */ + protected function printToc() + { + echo '

Table of Contents

'.PHP_EOL; + echo '
    '.PHP_EOL; + + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $title = $this->getTitle($documentation); + echo '
  • $title
  • ".PHP_EOL; + } + + echo '
'.PHP_EOL; + + }//end printToc() + + + /** + * Print the footer of the HTML page. + * + * @return void + */ + protected function printFooter() + { + // Turn off errors so we don't get timezone warnings if people + // don't have their timezone set. + $errorLevel = error_reporting(0); + echo '
'; + echo 'Documentation generated on '.date('r'); + echo ' by PHP_CodeSniffer '.Config::VERSION.''; + echo '
'.PHP_EOL; + error_reporting($errorLevel); + + echo ' '.PHP_EOL; + echo ''.PHP_EOL; + + }//end printFooter() + + + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + public function processSniff(\DOMNode $doc) + { + $title = $this->getTitle($doc); + echo ' '.PHP_EOL; + echo "

$title

".PHP_EOL; + + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + + }//end processSniff() + + + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $content = trim($node->nodeValue); + $content = htmlspecialchars($content); + + // Allow em tags only. + $content = str_replace('<em>', '', $content); + $content = str_replace('</em>', '', $content); + + echo "

$content

".PHP_EOL; + + }//end printTextBlock() + + + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + $first = trim($codeBlocks->item(0)->nodeValue); + $first = str_replace('', $first); + $first = str_replace(' ', ' ', $first); + $first = str_replace('', '', $first); + $first = str_replace('', '', $first); + + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + $second = trim($codeBlocks->item(1)->nodeValue); + $second = str_replace('', $second); + $second = str_replace(' ', ' ', $second); + $second = str_replace('', '', $second); + $second = str_replace('', '', $second); + + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo " ".PHP_EOL; + echo " ".PHP_EOL; + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo " ".PHP_EOL; + echo " ".PHP_EOL; + echo ' '.PHP_EOL; + echo '
$firstTitle$secondTitle
$first$second
'.PHP_EOL; + + }//end printCodeComparisonBlock() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php b/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php new file mode 100644 index 0000000..23bed27 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php @@ -0,0 +1,161 @@ + + * @copyright 2014 Arroba IT + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Config; + +class Markdown extends Generator +{ + + + /** + * Generates the documentation for a standard. + * + * @return void + * @see processSniff() + */ + public function generate() + { + ob_start(); + $this->printHeader(); + + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + + $this->printFooter(); + $content = ob_get_contents(); + ob_end_clean(); + + echo $content; + + }//end generate() + + + /** + * Print the markdown header. + * + * @return void + */ + protected function printHeader() + { + $standard = $this->ruleset->name; + + echo "# $standard Coding Standard".PHP_EOL; + + }//end printHeader() + + + /** + * Print the markdown footer. + * + * @return void + */ + protected function printFooter() + { + // Turn off errors so we don't get timezone warnings if people + // don't have their timezone set. + error_reporting(0); + echo 'Documentation generated on '.date('r'); + echo ' by [PHP_CodeSniffer '.Config::VERSION.'](https://github.com/PHPCSStandards/PHP_CodeSniffer)'.PHP_EOL; + + }//end printFooter() + + + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + protected function processSniff(\DOMNode $doc) + { + $title = $this->getTitle($doc); + echo PHP_EOL."## $title".PHP_EOL; + + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + + }//end processSniff() + + + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $content = trim($node->nodeValue); + $content = htmlspecialchars($content); + + $content = str_replace('<em>', '*', $content); + $content = str_replace('</em>', '*', $content); + + echo $content.PHP_EOL; + + }//end printTextBlock() + + + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + $first = trim($codeBlocks->item(0)->nodeValue); + $first = str_replace("\n", "\n ", $first); + $first = str_replace('', '', $first); + $first = str_replace('', '', $first); + + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + $second = trim($codeBlocks->item(1)->nodeValue); + $second = str_replace("\n", "\n ", $second); + $second = str_replace('', '', $second); + $second = str_replace('', '', $second); + + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo " ".PHP_EOL; + echo " ".PHP_EOL; + echo ' '.PHP_EOL; + echo ' '.PHP_EOL; + echo ''.PHP_EOL; + echo ''.PHP_EOL; + echo ' '.PHP_EOL; + echo '
$firstTitle$secondTitle
'.PHP_EOL.PHP_EOL; + echo " $first".PHP_EOL.PHP_EOL; + echo ''.PHP_EOL.PHP_EOL; + echo " $second".PHP_EOL.PHP_EOL; + echo '
'.PHP_EOL; + + }//end printCodeComparisonBlock() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Text.php b/vendor/squizlabs/php_codesniffer/src/Generators/Text.php new file mode 100644 index 0000000..7ec95ec --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Text.php @@ -0,0 +1,253 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Generators; + +class Text extends Generator +{ + + + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + public function processSniff(\DOMNode $doc) + { + $this->printTitle($doc); + + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + + }//end processSniff() + + + /** + * Prints the title area for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + protected function printTitle(\DOMNode $doc) + { + $title = $this->getTitle($doc); + $standard = $this->ruleset->name; + + echo PHP_EOL; + echo str_repeat('-', (strlen("$standard CODING STANDARD: $title") + 4)); + echo strtoupper(PHP_EOL."| $standard CODING STANDARD: $title |".PHP_EOL); + echo str_repeat('-', (strlen("$standard CODING STANDARD: $title") + 4)); + echo PHP_EOL.PHP_EOL; + + }//end printTitle() + + + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $text = trim($node->nodeValue); + $text = str_replace('', '*', $text); + $text = str_replace('', '*', $text); + + $nodeLines = explode("\n", $text); + $lines = []; + + foreach ($nodeLines as $currentLine) { + $currentLine = trim($currentLine); + if ($currentLine === '') { + // The text contained a blank line. Respect this. + $lines[] = ''; + continue; + } + + $tempLine = ''; + $words = explode(' ', $currentLine); + + foreach ($words as $word) { + $currentLength = strlen($tempLine.$word); + if ($currentLength < 99) { + $tempLine .= $word.' '; + continue; + } + + if ($currentLength === 99 || $currentLength === 100) { + // We are already at the edge, so we are done. + $lines[] = $tempLine.$word; + $tempLine = ''; + } else { + $lines[] = rtrim($tempLine); + $tempLine = $word.' '; + } + }//end foreach + + if ($tempLine !== '') { + $lines[] = rtrim($tempLine); + } + }//end foreach + + echo implode(PHP_EOL, $lines).PHP_EOL.PHP_EOL; + + }//end printTextBlock() + + + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + $first = trim($codeBlocks->item(0)->nodeValue); + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + + $firstTitleLines = []; + $tempTitle = ''; + $words = explode(' ', $firstTitle); + + foreach ($words as $word) { + if (strlen($tempTitle.$word) >= 45) { + if (strlen($tempTitle.$word) === 45) { + // Adding the extra space will push us to the edge + // so we are done. + $firstTitleLines[] = $tempTitle.$word; + $tempTitle = ''; + } else if (strlen($tempTitle.$word) === 46) { + // We are already at the edge, so we are done. + $firstTitleLines[] = $tempTitle.$word; + $tempTitle = ''; + } else { + $firstTitleLines[] = $tempTitle; + $tempTitle = $word.' '; + } + } else { + $tempTitle .= $word.' '; + } + }//end foreach + + if ($tempTitle !== '') { + $firstTitleLines[] = $tempTitle; + } + + $first = str_replace('', '', $first); + $first = str_replace('', '', $first); + $firstLines = explode("\n", $first); + + $second = trim($codeBlocks->item(1)->nodeValue); + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + + $secondTitleLines = []; + $tempTitle = ''; + $words = explode(' ', $secondTitle); + + foreach ($words as $word) { + if (strlen($tempTitle.$word) >= 45) { + if (strlen($tempTitle.$word) === 45) { + // Adding the extra space will push us to the edge + // so we are done. + $secondTitleLines[] = $tempTitle.$word; + $tempTitle = ''; + } else if (strlen($tempTitle.$word) === 46) { + // We are already at the edge, so we are done. + $secondTitleLines[] = $tempTitle.$word; + $tempTitle = ''; + } else { + $secondTitleLines[] = $tempTitle; + $tempTitle = $word.' '; + } + } else { + $tempTitle .= $word.' '; + } + }//end foreach + + if ($tempTitle !== '') { + $secondTitleLines[] = $tempTitle; + } + + $second = str_replace('', '', $second); + $second = str_replace('', '', $second); + $secondLines = explode("\n", $second); + + $maxCodeLines = max(count($firstLines), count($secondLines)); + $maxTitleLines = max(count($firstTitleLines), count($secondTitleLines)); + + echo str_repeat('-', 41); + echo ' CODE COMPARISON '; + echo str_repeat('-', 42).PHP_EOL; + + for ($i = 0; $i < $maxTitleLines; $i++) { + if (isset($firstTitleLines[$i]) === true) { + $firstLineText = $firstTitleLines[$i]; + } else { + $firstLineText = ''; + } + + if (isset($secondTitleLines[$i]) === true) { + $secondLineText = $secondTitleLines[$i]; + } else { + $secondLineText = ''; + } + + echo '| '; + echo $firstLineText.str_repeat(' ', (46 - strlen($firstLineText))); + echo ' | '; + echo $secondLineText.str_repeat(' ', (47 - strlen($secondLineText))); + echo ' |'.PHP_EOL; + }//end for + + echo str_repeat('-', 100).PHP_EOL; + + for ($i = 0; $i < $maxCodeLines; $i++) { + if (isset($firstLines[$i]) === true) { + $firstLineText = $firstLines[$i]; + } else { + $firstLineText = ''; + } + + if (isset($secondLines[$i]) === true) { + $secondLineText = $secondLines[$i]; + } else { + $secondLineText = ''; + } + + echo '| '; + echo $firstLineText.str_repeat(' ', max(0, (47 - strlen($firstLineText)))); + echo '| '; + echo $secondLineText.str_repeat(' ', max(0, (48 - strlen($secondLineText)))); + echo '|'.PHP_EOL; + }//end for + + echo str_repeat('-', 100).PHP_EOL.PHP_EOL; + + }//end printCodeComparisonBlock() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reporter.php b/vendor/squizlabs/php_codesniffer/src/Reporter.php new file mode 100644 index 0000000..3e3da32 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reporter.php @@ -0,0 +1,423 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Reports\Report; +use PHP_CodeSniffer\Util\Common; + +class Reporter +{ + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + + /** + * Total number of files that contain errors or warnings. + * + * @var integer + */ + public $totalFiles = 0; + + /** + * Total number of errors found during the run. + * + * @var integer + */ + public $totalErrors = 0; + + /** + * Total number of warnings found during the run. + * + * @var integer + */ + public $totalWarnings = 0; + + /** + * Total number of errors/warnings that can be fixed. + * + * @var integer + */ + public $totalFixable = 0; + + /** + * Total number of errors/warnings that were fixed. + * + * @var integer + */ + public $totalFixed = 0; + + /** + * When the PHPCS run started. + * + * @var float + */ + public static $startTime = 0; + + /** + * A cache of report objects. + * + * @var array + */ + private $reports = []; + + /** + * A cache of opened temporary files. + * + * @var array + */ + private $tmpFiles = []; + + + /** + * Initialise the reporter. + * + * All reports specified in the config will be created and their + * output file (or a temp file if none is specified) initialised by + * clearing the current contents. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a custom report class could not be found. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If a report class is incorrectly set up. + */ + public function __construct(Config $config) + { + $this->config = $config; + + foreach ($config->reports as $type => $output) { + if ($output === null) { + $output = $config->reportFile; + } + + $reportClassName = ''; + if (strpos($type, '.') !== false) { + // This is a path to a custom report class. + $filename = realpath($type); + if ($filename === false) { + $error = "ERROR: Custom report \"$type\" not found".PHP_EOL; + throw new DeepExitException($error, 3); + } + + $reportClassName = Autoload::loadFile($filename); + } else if (class_exists('PHP_CodeSniffer\Reports\\'.ucfirst($type)) === true) { + // PHPCS native report. + $reportClassName = 'PHP_CodeSniffer\Reports\\'.ucfirst($type); + } else if (class_exists($type) === true) { + // FQN of a custom report. + $reportClassName = $type; + } else { + // OK, so not a FQN, try and find the report using the registered namespaces. + $registeredNamespaces = Autoload::getSearchPaths(); + $trimmedType = ltrim($type, '\\'); + + foreach ($registeredNamespaces as $nsPrefix) { + if ($nsPrefix === '') { + continue; + } + + if (class_exists($nsPrefix.'\\'.$trimmedType) === true) { + $reportClassName = $nsPrefix.'\\'.$trimmedType; + break; + } + } + }//end if + + if ($reportClassName === '') { + $error = "ERROR: Class file for report \"$type\" not found".PHP_EOL; + throw new DeepExitException($error, 3); + } + + $reportClass = new $reportClassName(); + if (($reportClass instanceof Report) === false) { + throw new RuntimeException('Class "'.$reportClassName.'" must implement the "PHP_CodeSniffer\Report" interface.'); + } + + $this->reports[$type] = [ + 'output' => $output, + 'class' => $reportClass, + ]; + + if ($output === null) { + // Using a temp file. + // This needs to be set in the constructor so that all + // child procs use the same report file when running in parallel. + $this->tmpFiles[$type] = tempnam(sys_get_temp_dir(), 'phpcs'); + file_put_contents($this->tmpFiles[$type], ''); + } else { + file_put_contents($output, ''); + } + }//end foreach + + }//end __construct() + + + /** + * Generates and prints final versions of all reports. + * + * Returns TRUE if any of the reports output content to the screen + * or FALSE if all reports were silently printed to a file. + * + * @return bool + */ + public function printReports() + { + $toScreen = false; + foreach ($this->reports as $type => $report) { + if ($report['output'] === null) { + $toScreen = true; + } + + $this->printReport($type); + } + + return $toScreen; + + }//end printReports() + + + /** + * Generates and prints a single final report. + * + * @param string $report The report type to print. + * + * @return void + */ + public function printReport($report) + { + $reportClass = $this->reports[$report]['class']; + $reportFile = $this->reports[$report]['output']; + + if ($reportFile !== null) { + $filename = $reportFile; + $toScreen = false; + } else { + if (isset($this->tmpFiles[$report]) === true) { + $filename = $this->tmpFiles[$report]; + } else { + $filename = null; + } + + $toScreen = true; + } + + $reportCache = ''; + if ($filename !== null) { + $reportCache = file_get_contents($filename); + } + + ob_start(); + $reportClass->generate( + $reportCache, + $this->totalFiles, + $this->totalErrors, + $this->totalWarnings, + $this->totalFixable, + $this->config->showSources, + $this->config->reportWidth, + $this->config->interactive, + $toScreen + ); + $generatedReport = ob_get_contents(); + ob_end_clean(); + + if ($this->config->colors !== true || $reportFile !== null) { + $generatedReport = preg_replace('`\033\[[0-9;]+m`', '', $generatedReport); + } + + if ($reportFile !== null) { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo $generatedReport; + } + + file_put_contents($reportFile, $generatedReport.PHP_EOL); + } else { + echo $generatedReport; + if ($filename !== null && file_exists($filename) === true) { + unlink($filename); + unset($this->tmpFiles[$report]); + } + } + + }//end printReport() + + + /** + * Caches the result of a single processed file for all reports. + * + * The report content that is generated is appended to the output file + * assigned to each report. This content may be an intermediate report format + * and not reflect the final report output. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file that has been processed. + * + * @return void + */ + public function cacheFileReport(File $phpcsFile) + { + if (isset($this->config->reports) === false) { + // This happens during unit testing, or any time someone just wants + // the error data and not the printed report. + return; + } + + $reportData = $this->prepareFileReport($phpcsFile); + $errorsShown = false; + + foreach ($this->reports as $type => $report) { + $reportClass = $report['class']; + + ob_start(); + $result = $reportClass->generateFileReport($reportData, $phpcsFile, $this->config->showSources, $this->config->reportWidth); + if ($result === true) { + $errorsShown = true; + } + + $generatedReport = ob_get_contents(); + ob_end_clean(); + + if ($report['output'] === null) { + // Using a temp file. + if (isset($this->tmpFiles[$type]) === false) { + // When running in interactive mode, the reporter prints the full + // report many times, which will unlink the temp file. So we need + // to create a new one if it doesn't exist. + $this->tmpFiles[$type] = tempnam(sys_get_temp_dir(), 'phpcs'); + file_put_contents($this->tmpFiles[$type], ''); + } + + file_put_contents($this->tmpFiles[$type], $generatedReport, (FILE_APPEND | LOCK_EX)); + } else { + file_put_contents($report['output'], $generatedReport, (FILE_APPEND | LOCK_EX)); + }//end if + }//end foreach + + if ($errorsShown === true || PHP_CODESNIFFER_CBF === true) { + $this->totalFiles++; + $this->totalErrors += $reportData['errors']; + $this->totalWarnings += $reportData['warnings']; + + // When PHPCBF is running, we need to use the fixable error values + // after the report has run and fixed what it can. + if (PHP_CODESNIFFER_CBF === true) { + $this->totalFixable += $phpcsFile->getFixableCount(); + $this->totalFixed += $phpcsFile->getFixedCount(); + } else { + $this->totalFixable += $reportData['fixable']; + } + } + + }//end cacheFileReport() + + + /** + * Generate summary information to be used during report generation. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file that has been processed. + * + * @return array + */ + public function prepareFileReport(File $phpcsFile) + { + $report = [ + 'filename' => Common::stripBasepath($phpcsFile->getFilename(), $this->config->basepath), + 'errors' => $phpcsFile->getErrorCount(), + 'warnings' => $phpcsFile->getWarningCount(), + 'fixable' => $phpcsFile->getFixableCount(), + 'messages' => [], + ]; + + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Prefect score! + return $report; + } + + if ($this->config->recordErrors === false) { + $message = 'Errors are not being recorded but this report requires error messages. '; + $message .= 'This report will not show the correct information.'; + $report['messages'][1][1] = [ + [ + 'message' => $message, + 'source' => 'Internal.RecordErrors', + 'severity' => 5, + 'fixable' => false, + 'type' => 'ERROR', + ], + ]; + return $report; + } + + $errors = []; + + // Merge errors and warnings. + foreach ($phpcsFile->getErrors() as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + $newErrors = []; + foreach ($colErrors as $data) { + $newErrors[] = [ + 'message' => $data['message'], + 'source' => $data['source'], + 'severity' => $data['severity'], + 'fixable' => $data['fixable'], + 'type' => 'ERROR', + ]; + } + + $errors[$line][$column] = $newErrors; + } + + ksort($errors[$line]); + }//end foreach + + foreach ($phpcsFile->getWarnings() as $line => $lineWarnings) { + foreach ($lineWarnings as $column => $colWarnings) { + $newWarnings = []; + foreach ($colWarnings as $data) { + $newWarnings[] = [ + 'message' => $data['message'], + 'source' => $data['source'], + 'severity' => $data['severity'], + 'fixable' => $data['fixable'], + 'type' => 'WARNING', + ]; + } + + if (isset($errors[$line]) === false) { + $errors[$line] = []; + } + + if (isset($errors[$line][$column]) === true) { + $errors[$line][$column] = array_merge( + $newWarnings, + $errors[$line][$column] + ); + } else { + $errors[$line][$column] = $newWarnings; + } + }//end foreach + + ksort($errors[$line]); + }//end foreach + + ksort($errors); + $report['messages'] = $errors; + return $report; + + }//end prepareFileReport() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php b/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php new file mode 100644 index 0000000..b84f69f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php @@ -0,0 +1,253 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; + +class Cbf implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $errors = $phpcsFile->getFixableCount(); + if ($errors !== 0) { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + ob_end_clean(); + $startTime = microtime(true); + echo "\t=> Fixing file: $errors/$errors violations remaining"; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + } + + $fixed = $phpcsFile->fixer->fixFile(); + } + + if ($phpcsFile->config->stdin === true) { + // Replacing STDIN, so output current file to STDOUT + // even if nothing was fixed. Exit here because we + // can't process any more than 1 file in this setup. + $fixedContent = $phpcsFile->fixer->getContents(); + throw new DeepExitException($fixedContent, 1); + } + + if ($errors === 0) { + return false; + } + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + if ($fixed === false) { + echo 'ERROR'; + } else { + echo 'DONE'; + } + + $timeTaken = ((microtime(true) - $startTime) * 1000); + if ($timeTaken < 1000) { + $timeTaken = round($timeTaken); + echo " in {$timeTaken}ms".PHP_EOL; + } else { + $timeTaken = round(($timeTaken / 1000), 2); + echo " in $timeTaken secs".PHP_EOL; + } + } + + if ($fixed === true) { + // The filename in the report may be truncated due to a basepath setting + // but we are using it for writing here and not display, + // so find the correct path if basepath is in use. + $newFilename = $report['filename'].$phpcsFile->config->suffix; + if ($phpcsFile->config->basepath !== null) { + $newFilename = $phpcsFile->config->basepath.DIRECTORY_SEPARATOR.$newFilename; + } + + $newContent = $phpcsFile->fixer->getContents(); + file_put_contents($newFilename, $newContent); + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + if ($newFilename === $report['filename']) { + echo "\t=> File was overwritten".PHP_EOL; + } else { + echo "\t=> Fixed file written to ".basename($newFilename).PHP_EOL; + } + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + ob_start(); + } + + $errorCount = $phpcsFile->getErrorCount(); + $warningCount = $phpcsFile->getWarningCount(); + $fixableCount = $phpcsFile->getFixableCount(); + $fixedCount = ($errors - $fixableCount); + echo $report['filename'].">>$errorCount>>$warningCount>>$fixableCount>>$fixedCount".PHP_EOL; + + return $fixed; + + }//end generateFileReport() + + + /** + * Prints a summary of fixed files. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + echo PHP_EOL.'No fixable errors were found'.PHP_EOL; + return; + } + + $reportFiles = []; + $maxLength = 0; + $totalFixed = 0; + $failures = 0; + + foreach ($lines as $line) { + $parts = explode('>>', $line); + $fileLen = strlen($parts[0]); + $reportFiles[$parts[0]] = [ + 'errors' => $parts[1], + 'warnings' => $parts[2], + 'fixable' => $parts[3], + 'fixed' => $parts[4], + 'strlen' => $fileLen, + ]; + + $maxLength = max($maxLength, $fileLen); + + $totalFixed += $parts[4]; + + if ($parts[3] > 0) { + $failures++; + } + } + + $width = min($width, ($maxLength + 21)); + $width = max($width, 70); + + echo PHP_EOL."\033[1m".'PHPCBF RESULT SUMMARY'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1m".'FILE'.str_repeat(' ', ($width - 20)).'FIXED REMAINING'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + foreach ($reportFiles as $file => $data) { + $padding = ($width - 18 - $data['strlen']); + if ($padding < 0) { + $file = '...'.substr($file, (($padding * -1) + 3)); + $padding = 0; + } + + echo $file.str_repeat(' ', $padding).' '; + + if ($data['fixable'] > 0) { + echo "\033[31mFAILED TO FIX\033[0m".PHP_EOL; + continue; + } + + $remaining = ($data['errors'] + $data['warnings']); + + if ($data['fixed'] !== 0) { + echo $data['fixed']; + echo str_repeat(' ', (7 - strlen((string) $data['fixed']))); + } else { + echo '0 '; + } + + if ($remaining !== 0) { + echo $remaining; + } else { + echo '0'; + } + + echo PHP_EOL; + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1mA TOTAL OF $totalFixed ERROR"; + if ($totalFixed !== 1) { + echo 'S'; + } + + $numFiles = count($reportFiles); + echo ' WERE FIXED IN '.$numFiles.' FILE'; + if ($numFiles !== 1) { + echo 'S'; + } + + echo "\033[0m"; + + if ($failures > 0) { + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + echo "\033[1mPHPCBF FAILED TO FIX $failures FILE"; + if ($failures !== 1) { + echo 'S'; + } + + echo "\033[0m"; + } + + echo PHP_EOL.str_repeat('-', $width).PHP_EOL.PHP_EOL; + + if ($toScreen === true && $interactive === false) { + Util\Timing::printRunTime(); + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php b/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php new file mode 100644 index 0000000..dc1f6cc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php @@ -0,0 +1,109 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; + +class Checkstyle implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $out = new \XMLWriter; + $out->openMemory(); + $out->setIndent(true); + + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + $out->startElement('file'); + $out->writeAttribute('name', $report['filename']); + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['type'] = strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + + $out->startElement('error'); + $out->writeAttribute('line', $line); + $out->writeAttribute('column', $column); + $out->writeAttribute('severity', $error['type']); + $out->writeAttribute('message', $error['message']); + $out->writeAttribute('source', $error['source']); + $out->endElement(); + } + } + }//end foreach + + $out->endElement(); + echo $out->flush(); + + return true; + + }//end generateFileReport() + + + /** + * Prints all violations for processed files, in a Checkstyle format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo ''.PHP_EOL; + echo ''.PHP_EOL; + echo $cachedData; + echo ''.PHP_EOL; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Code.php b/vendor/squizlabs/php_codesniffer/src/Reports/Code.php new file mode 100644 index 0000000..2382705 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Code.php @@ -0,0 +1,362 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; + +class Code implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + // How many lines to show about and below the error line. + $surroundingLines = 2; + + $file = $report['filename']; + $tokens = $phpcsFile->getTokens(); + if (empty($tokens) === true) { + if (PHP_CODESNIFFER_VERBOSITY === 1) { + $startTime = microtime(true); + echo 'CODE report is parsing '.basename($file).' '; + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "CODE report is forcing parse of $file".PHP_EOL; + } + + try { + $phpcsFile->parse(); + } catch (\Exception $e) { + // This is a second parse, so ignore exceptions. + // They would have been added to the file's error list already. + } + + if (PHP_CODESNIFFER_VERBOSITY === 1) { + $timeTaken = ((microtime(true) - $startTime) * 1000); + if ($timeTaken < 1000) { + $timeTaken = round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = round(($timeTaken / 1000), 2); + echo "DONE in $timeTaken secs"; + } + + echo PHP_EOL; + } + + $tokens = $phpcsFile->getTokens(); + }//end if + + // Create an array that maps lines to the first token on the line. + $lineTokens = []; + $lastLine = 0; + $stackPtr = 0; + foreach ($tokens as $stackPtr => $token) { + if ($token['line'] !== $lastLine) { + if ($lastLine > 0) { + $lineTokens[$lastLine]['end'] = ($stackPtr - 1); + } + + $lastLine++; + $lineTokens[$lastLine] = [ + 'start' => $stackPtr, + 'end' => null, + ]; + } + } + + // Make sure the last token in the file sits on an imaginary + // last line so it is easier to generate code snippets at the + // end of the file. + $lineTokens[$lastLine]['end'] = $stackPtr; + + // Determine the longest code line we will be showing. + $maxSnippetLength = 0; + $eolLen = strlen($phpcsFile->eolChar); + foreach ($report['messages'] as $line => $lineErrors) { + $startLine = max(($line - $surroundingLines), 1); + $endLine = min(($line + $surroundingLines), $lastLine); + + $maxLineNumLength = strlen($endLine); + + for ($i = $startLine; $i <= $endLine; $i++) { + if ($i === 1) { + continue; + } + + $lineLength = ($tokens[($lineTokens[$i]['start'] - 1)]['column'] + $tokens[($lineTokens[$i]['start'] - 1)]['length'] - $eolLen); + $maxSnippetLength = max($lineLength, $maxSnippetLength); + } + } + + $maxSnippetLength += ($maxLineNumLength + 8); + + // Determine the longest error message we will be showing. + $maxErrorLength = 0; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $length = strlen($error['message']); + if ($showSources === true) { + $length += (strlen($error['source']) + 3); + } + + $maxErrorLength = max($maxErrorLength, ($length + 1)); + } + } + } + + // The padding that all lines will require that are printing an error message overflow. + if ($report['warnings'] > 0) { + $typeLength = 7; + } else { + $typeLength = 5; + } + + $errorPadding = str_repeat(' ', ($maxLineNumLength + 7)); + $errorPadding .= str_repeat(' ', $typeLength); + $errorPadding .= ' '; + if ($report['fixable'] > 0) { + $errorPadding .= ' '; + } + + $errorPaddingLength = strlen($errorPadding); + + // The maximum amount of space an error message can use. + $maxErrorSpace = ($width - $errorPaddingLength); + if ($showSources === true) { + // Account for the chars used to print colors. + $maxErrorSpace += 8; + } + + // Figure out the max report width we need and can use. + $fileLength = strlen($file); + $maxWidth = max(($fileLength + 6), ($maxErrorLength + $errorPaddingLength)); + $width = max(min($width, $maxWidth), $maxSnippetLength); + if ($width < 70) { + $width = 70; + } + + // Print the file header. + echo PHP_EOL."\033[1mFILE: "; + if ($fileLength <= ($width - 6)) { + echo $file; + } else { + echo '...'.substr($file, ($fileLength - ($width - 6))); + } + + echo "\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + echo "\033[1m".'FOUND '.$report['errors'].' ERROR'; + if ($report['errors'] !== 1) { + echo 'S'; + } + + if ($report['warnings'] > 0) { + echo ' AND '.$report['warnings'].' WARNING'; + if ($report['warnings'] !== 1) { + echo 'S'; + } + } + + echo ' AFFECTING '.count($report['messages']).' LINE'; + if (count($report['messages']) !== 1) { + echo 'S'; + } + + echo "\033[0m".PHP_EOL; + + foreach ($report['messages'] as $line => $lineErrors) { + $startLine = max(($line - $surroundingLines), 1); + $endLine = min(($line + $surroundingLines), $lastLine); + + $snippet = ''; + if (isset($lineTokens[$startLine]) === true) { + for ($i = $lineTokens[$startLine]['start']; $i <= $lineTokens[$endLine]['end']; $i++) { + $snippetLine = $tokens[$i]['line']; + if ($lineTokens[$snippetLine]['start'] === $i) { + // Starting a new line. + if ($snippetLine === $line) { + $snippet .= "\033[1m".'>> '; + } else { + $snippet .= ' '; + } + + $snippet .= str_repeat(' ', ($maxLineNumLength - strlen($snippetLine))); + $snippet .= $snippetLine.': '; + if ($snippetLine === $line) { + $snippet .= "\033[0m"; + } + } + + if (isset($tokens[$i]['orig_content']) === true) { + $tokenContent = $tokens[$i]['orig_content']; + } else { + $tokenContent = $tokens[$i]['content']; + } + + if (strpos($tokenContent, "\t") !== false) { + $token = $tokens[$i]; + $token['content'] = $tokenContent; + if (stripos(PHP_OS, 'WIN') === 0) { + $tab = "\000"; + } else { + $tab = "\033[30;1m»\033[0m"; + } + + $phpcsFile->tokenizer->replaceTabsInToken($token, $tab, "\000"); + $tokenContent = $token['content']; + } + + $tokenContent = Util\Common::prepareForOutput($tokenContent, ["\r", "\n", "\t"]); + $tokenContent = str_replace("\000", ' ', $tokenContent); + + $underline = false; + if ($snippetLine === $line && isset($lineErrors[$tokens[$i]['column']]) === true) { + $underline = true; + } + + // Underline invisible characters as well. + if ($underline === true && trim($tokenContent) === '') { + $snippet .= "\033[4m".' '."\033[0m".$tokenContent; + } else { + if ($underline === true) { + $snippet .= "\033[4m"; + } + + $snippet .= $tokenContent; + + if ($underline === true) { + $snippet .= "\033[0m"; + } + } + }//end for + }//end if + + echo str_repeat('-', $width).PHP_EOL; + + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $padding = ($maxLineNumLength - strlen($line)); + echo 'LINE '.str_repeat(' ', $padding).$line.': '; + + if ($error['type'] === 'ERROR') { + echo "\033[31mERROR\033[0m"; + if ($report['warnings'] > 0) { + echo ' '; + } + } else { + echo "\033[33mWARNING\033[0m"; + } + + echo ' '; + if ($report['fixable'] > 0) { + echo '['; + if ($error['fixable'] === true) { + echo 'x'; + } else { + echo ' '; + } + + echo '] '; + } + + $message = $error['message']; + $message = str_replace("\n", "\n".$errorPadding, $message); + if ($showSources === true) { + $message = "\033[1m".$message."\033[0m".' ('.$error['source'].')'; + } + + $errorMsg = wordwrap( + $message, + $maxErrorSpace, + PHP_EOL.$errorPadding + ); + + echo $errorMsg.PHP_EOL; + }//end foreach + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + echo rtrim($snippet).PHP_EOL; + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + if ($report['fixable'] > 0) { + echo "\033[1m".'PHPCBF CAN FIX THE '.$report['fixable'].' MARKED SNIFF VIOLATIONS AUTOMATICALLY'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + } + + return true; + + }//end generateFileReport() + + + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + if ($cachedData === '') { + return; + } + + echo $cachedData; + + if ($toScreen === true && $interactive === false) { + Util\Timing::printRunTime(); + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php b/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php new file mode 100644 index 0000000..aef7d7e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; + +class Csv implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $filename = str_replace('"', '\"', $report['filename']); + $message = str_replace('"', '\"', $error['message']); + $type = strtolower($error['type']); + $source = $error['source']; + $severity = $error['severity']; + $fixable = (int) $error['fixable']; + echo "\"$filename\",$line,$column,$type,\"$message\",$source,$severity,$fixable".PHP_EOL; + } + } + } + + return true; + + }//end generateFileReport() + + + /** + * Generates a csv report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo 'File,Line,Column,Type,Message,Source,Severity,Fixable'.PHP_EOL; + echo $cachedData; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php b/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php new file mode 100644 index 0000000..03f7bf2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php @@ -0,0 +1,130 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; + +class Diff implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $errors = $phpcsFile->getFixableCount(); + if ($errors === 0) { + return false; + } + + $phpcsFile->disableCaching(); + $tokens = $phpcsFile->getTokens(); + if (empty($tokens) === true) { + if (PHP_CODESNIFFER_VERBOSITY === 1) { + $startTime = microtime(true); + echo 'DIFF report is parsing '.basename($report['filename']).' '; + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo 'DIFF report is forcing parse of '.$report['filename'].PHP_EOL; + } + + $phpcsFile->parse(); + + if (PHP_CODESNIFFER_VERBOSITY === 1) { + $timeTaken = ((microtime(true) - $startTime) * 1000); + if ($timeTaken < 1000) { + $timeTaken = round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = round(($timeTaken / 1000), 2); + echo "DONE in $timeTaken secs"; + } + + echo PHP_EOL; + } + + $phpcsFile->fixer->startFile($phpcsFile); + }//end if + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + ob_end_clean(); + echo "\t*** START FILE FIXING ***".PHP_EOL; + } + + $fixed = $phpcsFile->fixer->fixFile(); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END FILE FIXING ***".PHP_EOL; + ob_start(); + } + + if ($fixed === false) { + return false; + } + + $diff = $phpcsFile->fixer->generateDiff(); + if ($diff === '') { + // Nothing to print. + return false; + } + + echo $diff.PHP_EOL; + return true; + + }//end generateFileReport() + + + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo $cachedData; + if ($toScreen === true && $cachedData !== '') { + echo PHP_EOL; + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php b/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php new file mode 100644 index 0000000..3f00365 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php @@ -0,0 +1,90 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; + +class Emacs implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $message = $error['message']; + if ($showSources === true) { + $message .= ' ('.$error['source'].')'; + } + + $type = strtolower($error['type']); + echo $report['filename'].':'.$line.':'.$column.': '.$type.' - '.$message.PHP_EOL; + } + } + } + + return true; + + }//end generateFileReport() + + + /** + * Generates an emacs report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo $cachedData; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Full.php b/vendor/squizlabs/php_codesniffer/src/Reports/Full.php new file mode 100644 index 0000000..d0b01da --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Full.php @@ -0,0 +1,259 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; + +class Full implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + // The length of the word ERROR or WARNING; used for padding. + if ($report['warnings'] > 0) { + $typeLength = 7; + } else { + $typeLength = 5; + } + + // Work out the max line number length for formatting. + $maxLineNumLength = max(array_map('strlen', array_keys($report['messages']))); + + // The padding that all lines will require that are + // printing an error message overflow. + $paddingLine2 = str_repeat(' ', ($maxLineNumLength + 1)); + $paddingLine2 .= ' | '; + $paddingLine2 .= str_repeat(' ', $typeLength); + $paddingLine2 .= ' | '; + if ($report['fixable'] > 0) { + $paddingLine2 .= ' '; + } + + $paddingLength = strlen($paddingLine2); + + // Make sure the report width isn't too big. + $maxErrorLength = 0; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + // Start with the presumption of a single line error message. + $length = strlen($error['message']); + $srcLength = (strlen($error['source']) + 3); + if ($showSources === true) { + $length += $srcLength; + } + + // ... but also handle multi-line messages correctly. + if (strpos($error['message'], "\n") !== false) { + $errorLines = explode("\n", $error['message']); + $length = max(array_map('strlen', $errorLines)); + + if ($showSources === true) { + $lastLine = array_pop($errorLines); + $length = max($length, (strlen($lastLine) + $srcLength)); + } + } + + $maxErrorLength = max($maxErrorLength, ($length + 1)); + }//end foreach + }//end foreach + }//end foreach + + $file = $report['filename']; + $fileLength = strlen($file); + $maxWidth = max(($fileLength + 6), ($maxErrorLength + $paddingLength)); + $width = min($width, $maxWidth); + if ($width < 70) { + $width = 70; + } + + echo PHP_EOL."\033[1mFILE: "; + if ($fileLength <= ($width - 6)) { + echo $file; + } else { + echo '...'.substr($file, ($fileLength - ($width - 6))); + } + + echo "\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + echo "\033[1m".'FOUND '.$report['errors'].' ERROR'; + if ($report['errors'] !== 1) { + echo 'S'; + } + + if ($report['warnings'] > 0) { + echo ' AND '.$report['warnings'].' WARNING'; + if ($report['warnings'] !== 1) { + echo 'S'; + } + } + + echo ' AFFECTING '.count($report['messages']).' LINE'; + if (count($report['messages']) !== 1) { + echo 'S'; + } + + echo "\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + // The maximum amount of space an error message can use. + $maxErrorSpace = ($width - $paddingLength - 1); + + $beforeMsg = ''; + $afterMsg = ''; + if ($showSources === true) { + $beforeMsg = "\033[1m"; + $afterMsg = "\033[0m"; + } + + $beforeAfterLength = strlen($beforeMsg.$afterMsg); + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $errorMsg = wordwrap( + $error['message'], + $maxErrorSpace + ); + + // Add the padding _after_ the wordwrap as the message itself may contain line breaks + // and those lines will also need to receive padding. + $errorMsg = str_replace("\n", $afterMsg.PHP_EOL.$paddingLine2.$beforeMsg, $errorMsg); + $errorMsg = $beforeMsg.$errorMsg.$afterMsg; + + if ($showSources === true) { + $lastMsg = $errorMsg; + $startPosLastLine = strrpos($errorMsg, PHP_EOL.$paddingLine2.$beforeMsg); + if ($startPosLastLine !== false) { + // Message is multiline. Grab the text of last line of the message, including the color codes. + $lastMsg = substr($errorMsg, ($startPosLastLine + strlen(PHP_EOL.$paddingLine2))); + } + + // When show sources is used, the message itself will be bolded, so we need to correct the length. + $sourceSuffix = '('.$error['source'].')'; + + $lastMsgPlusSourceLength = strlen($lastMsg); + // Add space + source suffix length. + $lastMsgPlusSourceLength += (1 + strlen($sourceSuffix)); + // Correct for the color codes. + $lastMsgPlusSourceLength -= $beforeAfterLength; + + if ($lastMsgPlusSourceLength > $maxErrorSpace) { + $errorMsg .= PHP_EOL.$paddingLine2.$sourceSuffix; + } else { + $errorMsg .= ' '.$sourceSuffix; + } + }//end if + + // The padding that goes on the front of the line. + $padding = ($maxLineNumLength - strlen($line)); + + echo ' '.str_repeat(' ', $padding).$line.' | '; + if ($error['type'] === 'ERROR') { + echo "\033[31mERROR\033[0m"; + if ($report['warnings'] > 0) { + echo ' '; + } + } else { + echo "\033[33mWARNING\033[0m"; + } + + echo ' | '; + if ($report['fixable'] > 0) { + echo '['; + if ($error['fixable'] === true) { + echo 'x'; + } else { + echo ' '; + } + + echo '] '; + } + + echo $errorMsg.PHP_EOL; + }//end foreach + }//end foreach + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + if ($report['fixable'] > 0) { + echo "\033[1m".'PHPCBF CAN FIX THE '.$report['fixable'].' MARKED SNIFF VIOLATIONS AUTOMATICALLY'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + } + + echo PHP_EOL; + return true; + + }//end generateFileReport() + + + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + if ($cachedData === '') { + return; + } + + echo $cachedData; + + if ($toScreen === true && $interactive === false) { + Util\Timing::printRunTime(); + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php new file mode 100644 index 0000000..3beb345 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php @@ -0,0 +1,91 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; + +class Gitblame extends VersionControl +{ + + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'GIT'; + + + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + $line = preg_replace('|\s+|', ' ', $line); + preg_match( + '|\(.+[0-9]{4}-[0-9]{2}-[0-9]{2}\s+[0-9]+\)|', + $line, + $blameParts + ); + + if (isset($blameParts[0]) === false) { + return false; + } + + $parts = explode(' ', $blameParts[0]); + + if (count($parts) < 2) { + return false; + } + + $parts = array_slice($parts, 0, (count($parts) - 2)); + $author = preg_replace('|\(|', '', implode(' ', $parts)); + return $author; + + }//end getAuthor() + + + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $cwd = getcwd(); + + chdir(dirname($filename)); + $command = 'git blame --date=short "'.basename($filename).'" 2>&1'; + $handle = popen($command, 'r'); + if ($handle === false) { + $error = 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + $rawContent = stream_get_contents($handle); + pclose($handle); + + $blames = explode("\n", $rawContent); + chdir($cwd); + + return $blames; + + }//end getBlameContent() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php new file mode 100644 index 0000000..2d98c46 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php @@ -0,0 +1,110 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; + +class Hgblame extends VersionControl +{ + + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'MERCURIAL'; + + + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return string|false String or FALSE if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + $line = preg_replace('|\s+|', ' ', $line); + + preg_match( + '|(.+[0-9]{2}:[0-9]{2}:[0-9]{2}\s[0-9]{4}\s.[0-9]{4}:)|', + $line, + $blameParts + ); + + if (isset($blameParts[0]) === false) { + return false; + } + + $parts = explode(' ', $blameParts[0]); + + if (count($parts) < 6) { + return false; + } + + $parts = array_slice($parts, 0, (count($parts) - 6)); + + return trim(preg_replace('|<.+>|', '', implode(' ', $parts))); + + }//end getAuthor() + + + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $cwd = getcwd(); + + $fileParts = explode(DIRECTORY_SEPARATOR, $filename); + $found = false; + $location = ''; + while (empty($fileParts) === false) { + array_pop($fileParts); + $location = implode(DIRECTORY_SEPARATOR, $fileParts); + if (is_dir($location.DIRECTORY_SEPARATOR.'.hg') === true) { + $found = true; + break; + } + } + + if ($found === true) { + chdir($location); + } else { + $error = 'ERROR: Could not locate .hg directory '.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + $command = 'hg blame -u -d -v "'.$filename.'" 2>&1'; + $handle = popen($command, 'r'); + if ($handle === false) { + $error = 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + $rawContent = stream_get_contents($handle); + pclose($handle); + + $blames = explode("\n", $rawContent); + chdir($cwd); + + return $blames; + + }//end getBlameContent() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Info.php b/vendor/squizlabs/php_codesniffer/src/Reports/Info.php new file mode 100644 index 0000000..4039056 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Info.php @@ -0,0 +1,172 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; + +class Info implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $metrics = $phpcsFile->getMetrics(); + foreach ($metrics as $metric => $data) { + foreach ($data['values'] as $value => $count) { + echo "$metric>>$value>>$count".PHP_EOL; + } + } + + return true; + + }//end generateFileReport() + + + /** + * Prints the recorded metrics. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + return; + } + + $metrics = []; + foreach ($lines as $line) { + $parts = explode('>>', $line); + $metric = $parts[0]; + $value = $parts[1]; + $count = $parts[2]; + if (isset($metrics[$metric]) === false) { + $metrics[$metric] = []; + } + + if (isset($metrics[$metric][$value]) === false) { + $metrics[$metric][$value] = $count; + } else { + $metrics[$metric][$value] += $count; + } + } + + ksort($metrics); + + echo PHP_EOL."\033[1m".'PHP CODE SNIFFER INFORMATION REPORT'."\033[0m".PHP_EOL; + echo str_repeat('-', 70).PHP_EOL; + + foreach ($metrics as $metric => $values) { + if (count($values) === 1) { + $count = reset($values); + $value = key($values); + + echo "$metric: \033[4m$value\033[0m [$count/$count, 100%]".PHP_EOL; + } else { + $totalCount = 0; + $valueWidth = 0; + foreach ($values as $value => $count) { + $totalCount += $count; + $valueWidth = max($valueWidth, strlen($value)); + } + + // Length of the total string, plus however many + // thousands separators there are. + $countWidth = strlen($totalCount); + $thousandSeparatorCount = floor($countWidth / 3); + $countWidth += $thousandSeparatorCount; + + // Account for 'total' line. + $valueWidth = max(5, $valueWidth); + + echo "$metric:".PHP_EOL; + + ksort($values, SORT_NATURAL); + arsort($values); + + $percentPrefixWidth = 0; + $percentWidth = 6; + foreach ($values as $value => $count) { + $percent = round(($count / $totalCount * 100), 2); + $percentPrefix = ''; + if ($percent === 0.00) { + $percent = 0.01; + $percentPrefix = '<'; + $percentPrefixWidth = 2; + $percentWidth = 4; + } + + printf( + "\t%-{$valueWidth}s => %{$countWidth}s (%{$percentPrefixWidth}s%{$percentWidth}.2f%%)".PHP_EOL, + $value, + number_format($count), + $percentPrefix, + $percent + ); + } + + echo "\t".str_repeat('-', ($valueWidth + $countWidth + 15)).PHP_EOL; + printf( + "\t%-{$valueWidth}s => %{$countWidth}s (100.00%%)".PHP_EOL, + 'total', + number_format($totalCount) + ); + }//end if + + echo PHP_EOL; + }//end foreach + + echo str_repeat('-', 70).PHP_EOL; + + if ($toScreen === true && $interactive === false) { + Timing::printRunTime(); + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Json.php b/vendor/squizlabs/php_codesniffer/src/Reports/Json.php new file mode 100644 index 0000000..0b9ad34 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Json.php @@ -0,0 +1,106 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; + +class Json implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $filename = str_replace('\\', '\\\\', $report['filename']); + $filename = str_replace('"', '\"', $filename); + $filename = str_replace('/', '\/', $filename); + echo '"'.$filename.'":{'; + echo '"errors":'.$report['errors'].',"warnings":'.$report['warnings'].',"messages":['; + + $messages = ''; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['message'] = str_replace("\n", '\n', $error['message']); + $error['message'] = str_replace("\r", '\r', $error['message']); + $error['message'] = str_replace("\t", '\t', $error['message']); + + $fixable = false; + if ($error['fixable'] === true) { + $fixable = true; + } + + $messagesObject = (object) $error; + $messagesObject->line = $line; + $messagesObject->column = $column; + $messagesObject->fixable = $fixable; + + $messages .= json_encode($messagesObject).","; + } + } + }//end foreach + + echo rtrim($messages, ','); + echo ']},'; + + return true; + + }//end generateFileReport() + + + /** + * Generates a JSON report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo '{"totals":{"errors":'.$totalErrors.',"warnings":'.$totalWarnings.',"fixable":'.$totalFixable.'},"files":{'; + echo rtrim($cachedData, ','); + echo "}}".PHP_EOL; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php b/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php new file mode 100644 index 0000000..40145a7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php @@ -0,0 +1,131 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; + +class Junit implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $out = new \XMLWriter; + $out->openMemory(); + $out->setIndent(true); + + $out->startElement('testsuite'); + $out->writeAttribute('name', $report['filename']); + $out->writeAttribute('errors', 0); + + if (count($report['messages']) === 0) { + $out->writeAttribute('tests', 1); + $out->writeAttribute('failures', 0); + + $out->startElement('testcase'); + $out->writeAttribute('name', $report['filename']); + $out->endElement(); + } else { + $failures = ($report['errors'] + $report['warnings']); + $out->writeAttribute('tests', $failures); + $out->writeAttribute('failures', $failures); + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $out->startElement('testcase'); + $out->writeAttribute('name', $error['source'].' at '.$report['filename']." ($line:$column)"); + + $error['type'] = strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + + $out->startElement('failure'); + $out->writeAttribute('type', $error['type']); + $out->writeAttribute('message', $error['message']); + $out->endElement(); + + $out->endElement(); + } + } + } + }//end if + + $out->endElement(); + echo $out->flush(); + return true; + + }//end generateFileReport() + + + /** + * Prints all violations for processed files, in a proprietary XML format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + // Figure out the total number of tests. + $tests = 0; + $matches = []; + preg_match_all('/tests="([0-9]+)"/', $cachedData, $matches); + if (isset($matches[1]) === true) { + foreach ($matches[1] as $match) { + $tests += $match; + } + } + + $failures = ($totalErrors + $totalWarnings); + echo ''.PHP_EOL; + echo ''.PHP_EOL; + echo $cachedData; + echo ''.PHP_EOL; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php b/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php new file mode 100644 index 0000000..1c29695 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php @@ -0,0 +1,242 @@ + + * @author Greg Sherwood + * @copyright 2012-2014 Christian Weiske + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Common; + +class Notifysend implements Report +{ + + /** + * Notification timeout in milliseconds. + * + * @var integer + */ + protected $timeout = 3000; + + /** + * Path to notify-send command. + * + * @var string + */ + protected $path = 'notify-send'; + + /** + * Show "ok, all fine" messages. + * + * @var boolean + */ + protected $showOk = true; + + /** + * Version of installed notify-send executable. + * + * @var string + */ + protected $version = null; + + + /** + * Load configuration data. + */ + public function __construct() + { + $path = Config::getExecutablePath('notifysend'); + if ($path !== null) { + $this->path = Common::escapeshellcmd($path); + } + + $timeout = Config::getConfigData('notifysend_timeout'); + if ($timeout !== null) { + $this->timeout = (int) $timeout; + } + + $showOk = Config::getConfigData('notifysend_showok'); + if ($showOk !== null) { + $this->showOk = (bool) $showOk; + } + + $this->version = str_replace( + 'notify-send ', + '', + exec($this->path.' --version') + ); + + }//end __construct() + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + echo $report['filename'].PHP_EOL; + + // We want this file counted in the total number + // of checked files even if it has no errors. + return true; + + }//end generateFileReport() + + + /** + * Generates a summary of errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $checkedFiles = explode(PHP_EOL, trim($cachedData)); + + $msg = $this->generateMessage($checkedFiles, $totalErrors, $totalWarnings); + if ($msg === null) { + if ($this->showOk === true) { + $this->notifyAllFine(); + } + } else { + $this->notifyErrors($msg); + } + + }//end generate() + + + /** + * Generate the error message to show to the user. + * + * @param string[] $checkedFiles The files checked during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * + * @return string|null Error message or NULL if no error/warning found. + */ + protected function generateMessage($checkedFiles, $totalErrors, $totalWarnings) + { + if ($totalErrors === 0 && $totalWarnings === 0) { + // Nothing to print. + return null; + } + + $totalFiles = count($checkedFiles); + + $msg = ''; + if ($totalFiles > 1) { + $msg .= 'Checked '.$totalFiles.' files'.PHP_EOL; + } else { + $msg .= $checkedFiles[0].PHP_EOL; + } + + if ($totalWarnings > 0) { + $msg .= $totalWarnings.' warnings'.PHP_EOL; + } + + if ($totalErrors > 0) { + $msg .= $totalErrors.' errors'.PHP_EOL; + } + + return $msg; + + }//end generateMessage() + + + /** + * Tell the user that all is fine and no error/warning has been found. + * + * @return void + */ + protected function notifyAllFine() + { + $cmd = $this->getBasicCommand(); + $cmd .= ' -i info'; + $cmd .= ' "PHP CodeSniffer: Ok"'; + $cmd .= ' "All fine"'; + exec($cmd); + + }//end notifyAllFine() + + + /** + * Tell the user that errors/warnings have been found. + * + * @param string $msg Message to display. + * + * @return void + */ + protected function notifyErrors($msg) + { + $cmd = $this->getBasicCommand(); + $cmd .= ' -i error'; + $cmd .= ' "PHP CodeSniffer: Error"'; + $cmd .= ' '.escapeshellarg(trim($msg)); + exec($cmd); + + }//end notifyErrors() + + + /** + * Generate and return the basic notify-send command string to execute. + * + * @return string Shell command with common parameters. + */ + protected function getBasicCommand() + { + $cmd = $this->path; + $cmd .= ' --category dev.validate'; + $cmd .= ' -h int:transient:1'; + $cmd .= ' -t '.(int) $this->timeout; + if (version_compare($this->version, '0.7.3', '>=') === true) { + $cmd .= ' -a phpcs'; + } + + return $cmd; + + }//end getBasicCommand() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Performance.php b/vendor/squizlabs/php_codesniffer/src/Reports/Performance.php new file mode 100644 index 0000000..ea90d0a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Performance.php @@ -0,0 +1,160 @@ + + * @copyright 2023 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Timing; + +class Performance implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $times = $phpcsFile->getListenerTimes(); + foreach ($times as $sniff => $time) { + echo "$sniff>>$time".PHP_EOL; + } + + return true; + + }//end generateFileReport() + + + /** + * Prints the sniff performance report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + return; + } + + // First collect the accumulated timings. + $timings = []; + $totalSniffTime = 0; + foreach ($lines as $line) { + $parts = explode('>>', $line); + $sniffClass = $parts[0]; + $time = $parts[1]; + + if (isset($timings[$sniffClass]) === false) { + $timings[$sniffClass] = 0; + } + + $timings[$sniffClass] += $time; + $totalSniffTime += $time; + } + + // Next, tidy up the sniff names and determine max needed column width. + $totalTimes = []; + $maxNameWidth = 0; + foreach ($timings as $sniffClass => $secs) { + $sniffCode = Common::getSniffCode($sniffClass); + $maxNameWidth = max($maxNameWidth, strlen($sniffCode)); + $totalTimes[$sniffCode] = $secs; + } + + // Leading space + up to 12 chars for the number. + $maxTimeWidth = 13; + // Leading space, open parenthesis, up to 5 chars for the number, space + % and close parenthesis. + $maxPercWidth = 10; + // Calculate the maximum width available for the sniff name. + $maxNameWidth = min(($width - $maxTimeWidth - $maxPercWidth), max(($width - $maxTimeWidth - $maxPercWidth), $maxNameWidth)); + + arsort($totalTimes); + + echo PHP_EOL."\033[1m".'PHP CODE SNIFFER SNIFF PERFORMANCE REPORT'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1m".'SNIFF'.str_repeat(' ', ($width - 31)).'TIME TAKEN (SECS) (%)'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + // Mark sniffs which take more than twice as long as the average processing time per sniff + // in orange and when they take more than three times as long as the average, + // mark them in red. + $avgSniffTime = ($totalSniffTime / count($totalTimes)); + $doubleAvgSniffTime = (2 * $avgSniffTime); + $tripleAvgSniffTime = (3 * $avgSniffTime); + + $format = "%- {$maxNameWidth}.{$maxNameWidth}s % 12.6f (% 5.1f %%)".PHP_EOL; + $formatBold = "\033[1m%- {$maxNameWidth}.{$maxNameWidth}s % 12.6f (% 5.1f %%)\033[0m".PHP_EOL; + $formatWarning = "%- {$maxNameWidth}.{$maxNameWidth}s \033[33m% 12.6f (% 5.1f %%)\033[0m".PHP_EOL; + $formatError = "%- {$maxNameWidth}.{$maxNameWidth}s \033[31m% 12.6f (% 5.1f %%)\033[0m".PHP_EOL; + + foreach ($totalTimes as $sniff => $time) { + $percent = round((($time / $totalSniffTime) * 100), 1); + + if ($time > $tripleAvgSniffTime) { + printf($formatError, $sniff, $time, $percent); + } else if ($time > $doubleAvgSniffTime) { + printf($formatWarning, $sniff, $time, $percent); + } else { + printf($format, $sniff, $time, $percent); + } + } + + echo str_repeat('-', $width).PHP_EOL; + printf($formatBold, 'TOTAL SNIFF PROCESSING TIME', $totalSniffTime, 100); + + $runTime = (Timing::getDuration() / 1000); + $phpcsTime = ($runTime - $totalSniffTime); + + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + printf($format, 'Time taken by sniffs', $totalSniffTime, round((($totalSniffTime / $runTime) * 100), 1)); + printf($format, 'Time taken by PHPCS runner', $phpcsTime, round((($phpcsTime / $runTime) * 100), 1)); + + echo str_repeat('-', $width).PHP_EOL; + printf($formatBold, 'TOTAL RUN TIME', $runTime, 100); + echo str_repeat('-', $width).PHP_EOL; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Report.php b/vendor/squizlabs/php_codesniffer/src/Reports/Report.php new file mode 100644 index 0000000..eec5eb1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Report.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; + +interface Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80); + + + /** + * Generate the actual report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ); + + +}//end interface diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Source.php b/vendor/squizlabs/php_codesniffer/src/Reports/Source.php new file mode 100644 index 0000000..6aa891a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Source.php @@ -0,0 +1,336 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; + +class Source implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + $sources = []; + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $src = $error['source']; + if (isset($sources[$src]) === false) { + $sources[$src] = [ + 'fixable' => (int) $error['fixable'], + 'count' => 1, + ]; + } else { + $sources[$src]['count']++; + } + } + } + } + + foreach ($sources as $source => $data) { + echo $source.'>>'.$data['fixable'].'>>'.$data['count'].PHP_EOL; + } + + return true; + + }//end generateFileReport() + + + /** + * Prints the source of all errors and warnings. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + return; + } + + $sources = []; + $maxLength = 0; + + foreach ($lines as $line) { + $parts = explode('>>', $line); + $source = $parts[0]; + $fixable = (bool) $parts[1]; + $count = $parts[2]; + + if (isset($sources[$source]) === false) { + if ($showSources === true) { + $parts = null; + $sniff = $source; + } else { + $parts = explode('.', $source); + if ($parts[0] === 'Internal') { + $parts[2] = $parts[1]; + $parts[1] = ''; + } + + $parts[1] = $this->makeFriendlyName($parts[1]); + + $sniff = $this->makeFriendlyName($parts[2]); + if (isset($parts[3]) === true) { + $name = $this->makeFriendlyName($parts[3]); + $name[0] = strtolower($name[0]); + $sniff .= ' '.$name; + unset($parts[3]); + } + + $parts[2] = $sniff; + }//end if + + $maxLength = max($maxLength, strlen($sniff)); + + $sources[$source] = [ + 'count' => $count, + 'fixable' => $fixable, + 'parts' => $parts, + ]; + } else { + $sources[$source]['count'] += $count; + }//end if + }//end foreach + + if ($showSources === true) { + $width = min($width, ($maxLength + 11)); + } else { + $width = min($width, ($maxLength + 41)); + } + + $width = max($width, 70); + + // Sort the data based on counts and source code. + $sourceCodes = array_keys($sources); + $counts = []; + foreach ($sources as $source => $data) { + $counts[$source] = $data['count']; + } + + array_multisort($counts, SORT_DESC, $sourceCodes, SORT_ASC, SORT_NATURAL, $sources); + + echo PHP_EOL."\033[1mPHP CODE SNIFFER VIOLATION SOURCE SUMMARY\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL."\033[1m"; + if ($showSources === true) { + if ($totalFixable > 0) { + echo ' SOURCE'.str_repeat(' ', ($width - 15)).'COUNT'.PHP_EOL; + } else { + echo 'SOURCE'.str_repeat(' ', ($width - 11)).'COUNT'.PHP_EOL; + } + } else { + if ($totalFixable > 0) { + echo ' STANDARD CATEGORY SNIFF'.str_repeat(' ', ($width - 44)).'COUNT'.PHP_EOL; + } else { + echo 'STANDARD CATEGORY SNIFF'.str_repeat(' ', ($width - 40)).'COUNT'.PHP_EOL; + } + } + + echo "\033[0m".str_repeat('-', $width).PHP_EOL; + + $fixableSources = 0; + + if ($showSources === true) { + $maxSniffWidth = ($width - 7); + } else { + $maxSniffWidth = ($width - 37); + } + + if ($totalFixable > 0) { + $maxSniffWidth -= 4; + } + + foreach ($sources as $source => $sourceData) { + if ($totalFixable > 0) { + echo '['; + if ($sourceData['fixable'] === true) { + echo 'x'; + $fixableSources++; + } else { + echo ' '; + } + + echo '] '; + } + + if ($showSources === true) { + if (strlen($source) > $maxSniffWidth) { + $source = substr($source, 0, $maxSniffWidth); + } + + echo $source; + if ($totalFixable > 0) { + echo str_repeat(' ', ($width - 9 - strlen($source))); + } else { + echo str_repeat(' ', ($width - 5 - strlen($source))); + } + } else { + $parts = $sourceData['parts']; + + if (strlen($parts[0]) > 8) { + $parts[0] = substr($parts[0], 0, ((strlen($parts[0]) - 8) * -1)); + } + + echo $parts[0].str_repeat(' ', (10 - strlen($parts[0]))); + + $category = $parts[1]; + if (strlen($category) > 18) { + $category = substr($category, 0, ((strlen($category) - 18) * -1)); + } + + echo $category.str_repeat(' ', (20 - strlen($category))); + + $sniff = $parts[2]; + if (strlen($sniff) > $maxSniffWidth) { + $sniff = substr($sniff, 0, $maxSniffWidth); + } + + if ($totalFixable > 0) { + echo $sniff.str_repeat(' ', ($width - 39 - strlen($sniff))); + } else { + echo $sniff.str_repeat(' ', ($width - 35 - strlen($sniff))); + } + }//end if + + echo $sourceData['count'].PHP_EOL; + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1m".'A TOTAL OF '.($totalErrors + $totalWarnings).' SNIFF VIOLATION'; + if (($totalErrors + $totalWarnings) > 1) { + echo 'S'; + } + + echo ' WERE FOUND IN '.count($sources).' SOURCE'; + if (count($sources) !== 1) { + echo 'S'; + } + + echo "\033[0m"; + + if ($totalFixable > 0) { + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + echo "\033[1mPHPCBF CAN FIX THE $fixableSources MARKED SOURCES AUTOMATICALLY ($totalFixable VIOLATIONS IN TOTAL)\033[0m"; + } + + echo PHP_EOL.str_repeat('-', $width).PHP_EOL.PHP_EOL; + + if ($toScreen === true && $interactive === false) { + Timing::printRunTime(); + } + + }//end generate() + + + /** + * Converts a camel caps name into a readable string. + * + * @param string $name The camel caps name to convert. + * + * @return string + */ + public function makeFriendlyName($name) + { + if (trim($name) === '') { + return ''; + } + + $friendlyName = ''; + $length = strlen($name); + + $lastWasUpper = false; + $lastWasNumeric = false; + for ($i = 0; $i < $length; $i++) { + if (is_numeric($name[$i]) === true) { + if ($lastWasNumeric === false) { + $friendlyName .= ' '; + } + + $lastWasUpper = false; + $lastWasNumeric = true; + } else { + $lastWasNumeric = false; + + $char = strtolower($name[$i]); + if ($char === $name[$i]) { + // Lowercase. + $lastWasUpper = false; + } else { + // Uppercase. + if ($lastWasUpper === false) { + $friendlyName .= ' '; + if ($i < ($length - 1)) { + $next = $name[($i + 1)]; + if (strtolower($next) === $next) { + // Next char is lowercase so it is a word boundary. + $name[$i] = strtolower($name[$i]); + } + } + } + + $lastWasUpper = true; + } + }//end if + + $friendlyName .= $name[$i]; + }//end for + + $friendlyName = trim($friendlyName); + $friendlyName[0] = strtoupper($friendlyName[0]); + + return $friendlyName; + + }//end makeFriendlyName() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php b/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php new file mode 100644 index 0000000..d2927a1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php @@ -0,0 +1,183 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; + +class Summary implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + if (PHP_CODESNIFFER_VERBOSITY === 0 + && $report['errors'] === 0 + && $report['warnings'] === 0 + ) { + // Nothing to print. + return false; + } + + echo $report['filename'].'>>'.$report['errors'].'>>'.$report['warnings'].PHP_EOL; + return true; + + }//end generateFileReport() + + + /** + * Generates a summary of errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + return; + } + + $reportFiles = []; + $maxLength = 0; + + foreach ($lines as $line) { + $parts = explode('>>', $line); + $fileLen = strlen($parts[0]); + $reportFiles[$parts[0]] = [ + 'errors' => $parts[1], + 'warnings' => $parts[2], + 'strlen' => $fileLen, + ]; + + $maxLength = max($maxLength, $fileLen); + } + + uksort( + $reportFiles, + function ($keyA, $keyB) { + $pathPartsA = explode(DIRECTORY_SEPARATOR, $keyA); + $pathPartsB = explode(DIRECTORY_SEPARATOR, $keyB); + + do { + $partA = array_shift($pathPartsA); + $partB = array_shift($pathPartsB); + } while ($partA === $partB && empty($pathPartsA) === false && empty($pathPartsB) === false); + + if (empty($pathPartsA) === false && empty($pathPartsB) === true) { + return 1; + } else if (empty($pathPartsA) === true && empty($pathPartsB) === false) { + return -1; + } else { + return strcasecmp($partA, $partB); + } + } + ); + + $width = min($width, ($maxLength + 21)); + $width = max($width, 70); + + echo PHP_EOL."\033[1m".'PHP CODE SNIFFER REPORT SUMMARY'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1m".'FILE'.str_repeat(' ', ($width - 20)).'ERRORS WARNINGS'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + + foreach ($reportFiles as $file => $data) { + $padding = ($width - 18 - $data['strlen']); + if ($padding < 0) { + $file = '...'.substr($file, (($padding * -1) + 3)); + $padding = 0; + } + + echo $file.str_repeat(' ', $padding).' '; + if ($data['errors'] !== 0) { + echo "\033[31m".$data['errors']."\033[0m"; + echo str_repeat(' ', (8 - strlen((string) $data['errors']))); + } else { + echo '0 '; + } + + if ($data['warnings'] !== 0) { + echo "\033[33m".$data['warnings']."\033[0m"; + } else { + echo '0'; + } + + echo PHP_EOL; + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1mA TOTAL OF $totalErrors ERROR"; + if ($totalErrors !== 1) { + echo 'S'; + } + + echo ' AND '.$totalWarnings.' WARNING'; + if ($totalWarnings !== 1) { + echo 'S'; + } + + echo ' WERE FOUND IN '.$totalFiles.' FILE'; + if ($totalFiles !== 1) { + echo 'S'; + } + + echo "\033[0m"; + + if ($totalFixable > 0) { + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + echo "\033[1mPHPCBF CAN FIX $totalFixable OF THESE SNIFF VIOLATIONS AUTOMATICALLY\033[0m"; + } + + echo PHP_EOL.str_repeat('-', $width).PHP_EOL.PHP_EOL; + + if ($toScreen === true && $interactive === false) { + Util\Timing::printRunTime(); + } + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php new file mode 100644 index 0000000..b44e83d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php @@ -0,0 +1,73 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; + +class Svnblame extends VersionControl +{ + + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'SVN'; + + + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + preg_match('|\s*([^\s]+)\s+([^\s]+)|', $line, $blameParts); + + if (isset($blameParts[2]) === false) { + return false; + } + + return $blameParts[2]; + + }//end getAuthor() + + + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $command = 'svn blame "'.$filename.'" 2>&1'; + $handle = popen($command, 'r'); + if ($handle === false) { + $error = 'ERROR: Could not execute "'.$command.'"'.PHP_EOL.PHP_EOL; + throw new DeepExitException($error, 3); + } + + $rawContent = stream_get_contents($handle); + pclose($handle); + + $blames = explode("\n", $rawContent); + + return $blames; + + }//end getBlameContent() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php b/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php new file mode 100644 index 0000000..e3ad74b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php @@ -0,0 +1,376 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; + +abstract class VersionControl implements Report +{ + + /** + * The name of the report we want in the output. + * + * @var string + */ + protected $reportName = 'VERSION CONTROL'; + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $blames = $this->getBlameContent($phpcsFile->getFilename()); + + $authorCache = []; + $praiseCache = []; + $sourceCache = []; + + foreach ($report['messages'] as $line => $lineErrors) { + $author = 'Unknown'; + if (isset($blames[($line - 1)]) === true) { + $blameAuthor = $this->getAuthor($blames[($line - 1)]); + if ($blameAuthor !== false) { + $author = $blameAuthor; + } + } + + if (isset($authorCache[$author]) === false) { + $authorCache[$author] = 0; + $praiseCache[$author] = [ + 'good' => 0, + 'bad' => 0, + ]; + } + + $praiseCache[$author]['bad']++; + + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $authorCache[$author]++; + + if ($showSources === true) { + $source = $error['source']; + if (isset($sourceCache[$author][$source]) === false) { + $sourceCache[$author][$source] = [ + 'count' => 1, + 'fixable' => $error['fixable'], + ]; + } else { + $sourceCache[$author][$source]['count']++; + } + } + } + } + + unset($blames[($line - 1)]); + }//end foreach + + // Now go through and give the authors some credit for + // all the lines that do not have errors. + foreach ($blames as $line) { + $author = $this->getAuthor($line); + if ($author === false) { + $author = 'Unknown'; + } + + if (isset($authorCache[$author]) === false) { + // This author doesn't have any errors. + if (PHP_CODESNIFFER_VERBOSITY === 0) { + continue; + } + + $authorCache[$author] = 0; + $praiseCache[$author] = [ + 'good' => 0, + 'bad' => 0, + ]; + } + + $praiseCache[$author]['good']++; + }//end foreach + + foreach ($authorCache as $author => $errors) { + echo "AUTHOR>>$author>>$errors".PHP_EOL; + } + + foreach ($praiseCache as $author => $praise) { + echo "PRAISE>>$author>>".$praise['good'].'>>'.$praise['bad'].PHP_EOL; + } + + foreach ($sourceCache as $author => $sources) { + foreach ($sources as $source => $sourceData) { + $count = $sourceData['count']; + $fixable = (int) $sourceData['fixable']; + echo "SOURCE>>$author>>$source>>$count>>$fixable".PHP_EOL; + } + } + + return true; + + }//end generateFileReport() + + + /** + * Prints the author of all errors and warnings, as given by "version control blame". + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + $errorsShown = ($totalErrors + $totalWarnings); + if ($errorsShown === 0) { + // Nothing to show. + return; + } + + $lines = explode(PHP_EOL, $cachedData); + array_pop($lines); + + if (empty($lines) === true) { + return; + } + + $authorCache = []; + $praiseCache = []; + $sourceCache = []; + + foreach ($lines as $line) { + $parts = explode('>>', $line); + switch ($parts[0]) { + case 'AUTHOR': + if (isset($authorCache[$parts[1]]) === false) { + $authorCache[$parts[1]] = $parts[2]; + } else { + $authorCache[$parts[1]] += $parts[2]; + } + break; + case 'PRAISE': + if (isset($praiseCache[$parts[1]]) === false) { + $praiseCache[$parts[1]] = [ + 'good' => $parts[2], + 'bad' => $parts[3], + ]; + } else { + $praiseCache[$parts[1]]['good'] += $parts[2]; + $praiseCache[$parts[1]]['bad'] += $parts[3]; + } + break; + case 'SOURCE': + if (isset($praiseCache[$parts[1]]) === false) { + $praiseCache[$parts[1]] = []; + } + + if (isset($sourceCache[$parts[1]][$parts[2]]) === false) { + $sourceCache[$parts[1]][$parts[2]] = [ + 'count' => $parts[3], + 'fixable' => (bool) $parts[4], + ]; + } else { + $sourceCache[$parts[1]][$parts[2]]['count'] += $parts[3]; + } + break; + default: + break; + }//end switch + }//end foreach + + // Make sure the report width isn't too big. + $maxLength = 0; + foreach ($authorCache as $author => $count) { + $maxLength = max($maxLength, strlen($author)); + if ($showSources === true && isset($sourceCache[$author]) === true) { + foreach ($sourceCache[$author] as $source => $sourceData) { + if ($source === 'count') { + continue; + } + + $maxLength = max($maxLength, (strlen($source) + 9)); + } + } + } + + $width = min($width, ($maxLength + 30)); + $width = max($width, 70); + arsort($authorCache); + + echo PHP_EOL."\033[1m".'PHP CODE SNIFFER '.$this->reportName.' BLAME SUMMARY'."\033[0m".PHP_EOL; + echo str_repeat('-', $width).PHP_EOL."\033[1m"; + if ($showSources === true) { + echo 'AUTHOR SOURCE'.str_repeat(' ', ($width - 43)).'(Author %) (Overall %) COUNT'.PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + } else { + echo 'AUTHOR'.str_repeat(' ', ($width - 34)).'(Author %) (Overall %) COUNT'.PHP_EOL; + echo str_repeat('-', $width).PHP_EOL; + } + + echo "\033[0m"; + + if ($showSources === true) { + $maxSniffWidth = ($width - 15); + + if ($totalFixable > 0) { + $maxSniffWidth -= 4; + } + } + + $fixableSources = 0; + + foreach ($authorCache as $author => $count) { + if ($praiseCache[$author]['good'] === 0) { + $percent = 0; + } else { + $total = ($praiseCache[$author]['bad'] + $praiseCache[$author]['good']); + $percent = round(($praiseCache[$author]['bad'] / $total * 100), 2); + } + + $overallPercent = '('.round((($count / $errorsShown) * 100), 2).')'; + $authorPercent = '('.$percent.')'; + $line = str_repeat(' ', (6 - strlen($count))).$count; + $line = str_repeat(' ', (12 - strlen($overallPercent))).$overallPercent.$line; + $line = str_repeat(' ', (11 - strlen($authorPercent))).$authorPercent.$line; + $line = $author.str_repeat(' ', ($width - strlen($author) - strlen($line))).$line; + + if ($showSources === true) { + $line = "\033[1m$line\033[0m"; + } + + echo $line.PHP_EOL; + + if ($showSources === true && isset($sourceCache[$author]) === true) { + $errors = $sourceCache[$author]; + asort($errors); + $errors = array_reverse($errors); + + foreach ($errors as $source => $sourceData) { + if ($source === 'count') { + continue; + } + + $count = $sourceData['count']; + + $srcLength = strlen($source); + if ($srcLength > $maxSniffWidth) { + $source = substr($source, 0, $maxSniffWidth); + } + + $line = str_repeat(' ', (5 - strlen($count))).$count; + + echo ' '; + if ($totalFixable > 0) { + echo '['; + if ($sourceData['fixable'] === true) { + echo 'x'; + $fixableSources++; + } else { + echo ' '; + } + + echo '] '; + } + + echo $source; + if ($totalFixable > 0) { + echo str_repeat(' ', ($width - 18 - strlen($source))); + } else { + echo str_repeat(' ', ($width - 14 - strlen($source))); + } + + echo $line.PHP_EOL; + }//end foreach + }//end if + }//end foreach + + echo str_repeat('-', $width).PHP_EOL; + echo "\033[1m".'A TOTAL OF '.$errorsShown.' SNIFF VIOLATION'; + if ($errorsShown !== 1) { + echo 'S'; + } + + echo ' WERE COMMITTED BY '.count($authorCache).' AUTHOR'; + if (count($authorCache) !== 1) { + echo 'S'; + } + + echo "\033[0m"; + + if ($totalFixable > 0) { + if ($showSources === true) { + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + echo "\033[1mPHPCBF CAN FIX THE $fixableSources MARKED SOURCES AUTOMATICALLY ($totalFixable VIOLATIONS IN TOTAL)\033[0m"; + } else { + echo PHP_EOL.str_repeat('-', $width).PHP_EOL; + echo "\033[1mPHPCBF CAN FIX $totalFixable OF THESE SNIFF VIOLATIONS AUTOMATICALLY\033[0m"; + } + } + + echo PHP_EOL.str_repeat('-', $width).PHP_EOL.PHP_EOL; + + if ($toScreen === true && $interactive === false) { + Timing::printRunTime(); + } + + }//end generate() + + + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + abstract protected function getAuthor($line); + + + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + */ + abstract protected function getBlameContent($filename); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php b/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php new file mode 100644 index 0000000..dc25bba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php @@ -0,0 +1,126 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; + +class Xml implements Report +{ + + + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80) + { + $out = new \XMLWriter; + $out->openMemory(); + $out->setIndent(true); + $out->setIndentString(' '); + $out->startDocument('1.0', 'UTF-8'); + + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return false; + } + + $out->startElement('file'); + $out->writeAttribute('name', $report['filename']); + $out->writeAttribute('errors', $report['errors']); + $out->writeAttribute('warnings', $report['warnings']); + $out->writeAttribute('fixable', $report['fixable']); + + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['type'] = strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + + $out->startElement($error['type']); + $out->writeAttribute('line', $line); + $out->writeAttribute('column', $column); + $out->writeAttribute('source', $error['source']); + $out->writeAttribute('severity', $error['severity']); + $out->writeAttribute('fixable', (int) $error['fixable']); + $out->text($error['message']); + $out->endElement(); + } + } + }//end foreach + + $out->endElement(); + + // Remove the start of the document because we will + // add that manually later. We only have it in here to + // properly set the encoding. + $content = $out->flush(); + if (strpos($content, PHP_EOL) !== false) { + $content = substr($content, (strpos($content, PHP_EOL) + strlen(PHP_EOL))); + } else if (strpos($content, "\n") !== false) { + $content = substr($content, (strpos($content, "\n") + 1)); + } + + echo $content; + + return true; + + }//end generateFileReport() + + + /** + * Prints all violations for processed files, in a proprietary XML format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate( + $cachedData, + $totalFiles, + $totalErrors, + $totalWarnings, + $totalFixable, + $showSources=false, + $width=80, + $interactive=false, + $toScreen=true + ) { + echo ''.PHP_EOL; + echo ''.PHP_EOL; + echo $cachedData; + echo ''.PHP_EOL; + + }//end generate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Ruleset.php b/vendor/squizlabs/php_codesniffer/src/Ruleset.php new file mode 100644 index 0000000..2e24930 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Ruleset.php @@ -0,0 +1,1455 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Util; +use stdClass; + +class Ruleset +{ + + /** + * The name of the coding standard being used. + * + * If a top-level standard includes other standards, or sniffs + * from other standards, only the name of the top-level standard + * will be stored in here. + * + * If multiple top-level standards are being loaded into + * a single ruleset object, this will store a comma separated list + * of the top-level standard names. + * + * @var string + */ + public $name = ''; + + /** + * A list of file paths for the ruleset files being used. + * + * @var string[] + */ + public $paths = []; + + /** + * A list of regular expressions used to ignore specific sniffs for files and folders. + * + * Is also used to set global exclude patterns. + * The key is the regular expression and the value is the type + * of ignore pattern (absolute or relative). + * + * @var array + */ + public $ignorePatterns = []; + + /** + * A list of regular expressions used to include specific sniffs for files and folders. + * + * The key is the sniff code and the value is an array with + * the key being a regular expression and the value is the type + * of ignore pattern (absolute or relative). + * + * @var array> + */ + public $includePatterns = []; + + /** + * An array of sniff objects that are being used to check files. + * + * The key is the fully qualified name of the sniff class + * and the value is the sniff object. + * + * @var array + */ + public $sniffs = []; + + /** + * A mapping of sniff codes to fully qualified class names. + * + * The key is the sniff code and the value + * is the fully qualified name of the sniff class. + * + * @var array + */ + public $sniffCodes = []; + + /** + * An array of token types and the sniffs that are listening for them. + * + * The key is the token name being listened for and the value + * is the sniff object. + * + * @var array>> + */ + public $tokenListeners = []; + + /** + * An array of rules from the ruleset.xml file. + * + * It may be empty, indicating that the ruleset does not override + * any of the default sniff settings. + * + * @var array + */ + public $ruleset = []; + + /** + * The directories that the processed rulesets are in. + * + * @var string[] + */ + protected $rulesetDirs = []; + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + private $config = null; + + + /** + * Initialise the ruleset that the run will use. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If no sniffs were registered. + */ + public function __construct(Config $config) + { + $this->config = $config; + $restrictions = $config->sniffs; + $exclusions = $config->exclude; + $sniffs = []; + + $standardPaths = []; + foreach ($config->standards as $standard) { + $installed = Util\Standards::getInstalledStandardPath($standard); + if ($installed === null) { + $standard = Util\Common::realpath($standard); + if (is_dir($standard) === true + && is_file(Util\Common::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml')) === true + ) { + $standard = Util\Common::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml'); + } + } else { + $standard = $installed; + } + + $standardPaths[] = $standard; + } + + foreach ($standardPaths as $standard) { + $ruleset = @simplexml_load_string(file_get_contents($standard)); + if ($ruleset !== false) { + $standardName = (string) $ruleset['name']; + if ($this->name !== '') { + $this->name .= ', '; + } + + $this->name .= $standardName; + + // Allow autoloading of custom files inside this standard. + if (isset($ruleset['namespace']) === true) { + $namespace = (string) $ruleset['namespace']; + } else { + $namespace = basename(dirname($standard)); + } + + Autoload::addSearchPath(dirname($standard), $namespace); + } + + if (defined('PHP_CODESNIFFER_IN_TESTS') === true && empty($restrictions) === false) { + // In unit tests, only register the sniffs that the test wants and not the entire standard. + try { + foreach ($restrictions as $restriction) { + $sniffs = array_merge($sniffs, $this->expandRulesetReference($restriction, dirname($standard))); + } + } catch (RuntimeException $e) { + // Sniff reference could not be expanded, which probably means this + // is an installed standard. Let the unit test system take care of + // setting the correct sniff for testing. + return; + } + + break; + } + + if (PHP_CODESNIFFER_VERBOSITY === 1) { + echo "Registering sniffs in the $standardName standard... "; + if (count($config->standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) { + echo PHP_EOL; + } + } + + $sniffs = array_merge($sniffs, $this->processRuleset($standard)); + }//end foreach + + // Ignore sniff restrictions if caching is on. + if ($config->cache === true) { + $restrictions = []; + $exclusions = []; + } + + $sniffRestrictions = []; + foreach ($restrictions as $sniffCode) { + $parts = explode('.', strtolower($sniffCode)); + $sniffName = $parts[0].'\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff'; + $sniffRestrictions[$sniffName] = true; + } + + $sniffExclusions = []; + foreach ($exclusions as $sniffCode) { + $parts = explode('.', strtolower($sniffCode)); + $sniffName = $parts[0].'\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff'; + $sniffExclusions[$sniffName] = true; + } + + $this->registerSniffs($sniffs, $sniffRestrictions, $sniffExclusions); + $this->populateTokenListeners(); + + $numSniffs = count($this->sniffs); + if (PHP_CODESNIFFER_VERBOSITY === 1) { + echo "DONE ($numSniffs sniffs registered)".PHP_EOL; + } + + if ($numSniffs === 0) { + throw new RuntimeException('No sniffs were registered'); + } + + }//end __construct() + + + /** + * Prints a report showing the sniffs contained in a standard. + * + * @return void + */ + public function explain() + { + $sniffs = array_keys($this->sniffCodes); + sort($sniffs, (SORT_NATURAL | SORT_FLAG_CASE)); + + $sniffCount = count($sniffs); + + // Add a dummy entry to the end so we loop one last time + // and echo out the collected info about the last standard. + $sniffs[] = ''; + + $summaryLine = PHP_EOL."The $this->name standard contains 1 sniff".PHP_EOL; + if ($sniffCount !== 1) { + $summaryLine = str_replace('1 sniff', "$sniffCount sniffs", $summaryLine); + } + + echo $summaryLine; + + $lastStandard = null; + $lastCount = 0; + $sniffsInStandard = []; + + foreach ($sniffs as $i => $sniff) { + if ($i === $sniffCount) { + $currentStandard = null; + } else { + $currentStandard = substr($sniff, 0, strpos($sniff, '.')); + if ($lastStandard === null) { + $lastStandard = $currentStandard; + } + } + + // Reached the first item in the next standard. + // Echo out the info collected from the previous standard. + if ($currentStandard !== $lastStandard) { + $subTitle = $lastStandard.' ('.$lastCount.' sniff'; + if ($lastCount > 1) { + $subTitle .= 's'; + } + + $subTitle .= ')'; + + echo PHP_EOL.$subTitle.PHP_EOL; + echo str_repeat('-', strlen($subTitle)).PHP_EOL; + echo ' '.implode(PHP_EOL.' ', $sniffsInStandard).PHP_EOL; + + $lastStandard = $currentStandard; + $lastCount = 0; + $sniffsInStandard = []; + + if ($currentStandard === null) { + break; + } + }//end if + + $sniffsInStandard[] = $sniff; + ++$lastCount; + }//end foreach + + }//end explain() + + + /** + * Processes a single ruleset and returns a list of the sniffs it represents. + * + * Rules founds within the ruleset are processed immediately, but sniff classes + * are not registered by this method. + * + * @param string $rulesetPath The path to a ruleset XML file. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return string[] + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException - If the ruleset path is invalid. + * - If a specified autoload file could not be found. + */ + public function processRuleset($rulesetPath, $depth=0) + { + $rulesetPath = Util\Common::realpath($rulesetPath); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo 'Processing ruleset '.Util\Common::stripBasepath($rulesetPath, $this->config->basepath).PHP_EOL; + } + + libxml_use_internal_errors(true); + $ruleset = simplexml_load_string(file_get_contents($rulesetPath)); + if ($ruleset === false) { + $errorMsg = "Ruleset $rulesetPath is not valid".PHP_EOL; + $errors = libxml_get_errors(); + foreach ($errors as $error) { + $errorMsg .= '- On line '.$error->line.', column '.$error->column.': '.$error->message; + } + + libxml_clear_errors(); + throw new RuntimeException($errorMsg); + } + + libxml_use_internal_errors(false); + + $ownSniffs = []; + $includedSniffs = []; + $excludedSniffs = []; + + $this->paths[] = $rulesetPath; + $rulesetDir = dirname($rulesetPath); + $this->rulesetDirs[] = $rulesetDir; + + $sniffDir = $rulesetDir.DIRECTORY_SEPARATOR.'Sniffs'; + if (is_dir($sniffDir) === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\tAdding sniff files from ".Util\Common::stripBasepath($sniffDir, $this->config->basepath).' directory'.PHP_EOL; + } + + $ownSniffs = $this->expandSniffDirectory($sniffDir, $depth); + } + + // Include custom autoloaders. + foreach ($ruleset->{'autoload'} as $autoload) { + if ($this->shouldProcessElement($autoload) === false) { + continue; + } + + $autoloadPath = (string) $autoload; + + // Try relative autoload paths first. + $relativePath = Util\Common::realPath(dirname($rulesetPath).DIRECTORY_SEPARATOR.$autoloadPath); + + if ($relativePath !== false && is_file($relativePath) === true) { + $autoloadPath = $relativePath; + } else if (is_file($autoloadPath) === false) { + throw new RuntimeException('The specified autoload file "'.$autoload.'" does not exist'); + } + + include_once $autoloadPath; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> included autoloader $autoloadPath".PHP_EOL; + } + }//end foreach + + // Process custom sniff config settings. + foreach ($ruleset->{'config'} as $config) { + if ($this->shouldProcessElement($config) === false) { + continue; + } + + Config::setConfigData((string) $config['name'], (string) $config['value'], true); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> set config value ".(string) $config['name'].': '.(string) $config['value'].PHP_EOL; + } + } + + foreach ($ruleset->rule as $rule) { + if (isset($rule['ref']) === false + || $this->shouldProcessElement($rule) === false + ) { + continue; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\tProcessing rule \"".$rule['ref'].'"'.PHP_EOL; + } + + $expandedSniffs = $this->expandRulesetReference((string) $rule['ref'], $rulesetDir, $depth); + $newSniffs = array_diff($expandedSniffs, $includedSniffs); + $includedSniffs = array_merge($includedSniffs, $expandedSniffs); + + $parts = explode('.', $rule['ref']); + if (count($parts) === 4 + && $parts[0] !== '' + && $parts[1] !== '' + && $parts[2] !== '' + ) { + $sniffCode = $parts[0].'.'.$parts[1].'.'.$parts[2]; + if (isset($this->ruleset[$sniffCode]['severity']) === true + && $this->ruleset[$sniffCode]['severity'] === 0 + ) { + // This sniff code has already been turned off, but now + // it is being explicitly included again, so turn it back on. + $this->ruleset[(string) $rule['ref']]['severity'] = 5; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* disabling sniff exclusion for specific message code *".PHP_EOL; + echo str_repeat("\t", $depth); + echo "\t\t=> severity set to 5".PHP_EOL; + } + } else if (empty($newSniffs) === false) { + $newSniff = $newSniffs[0]; + if (in_array($newSniff, $ownSniffs, true) === false) { + // Including a sniff that hasn't been included higher up, but + // only including a single message from it. So turn off all messages in + // the sniff, except this one. + $this->ruleset[$sniffCode]['severity'] = 0; + $this->ruleset[(string) $rule['ref']]['severity'] = 5; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\tExcluding sniff \"".$sniffCode.'" except for "'.$parts[3].'"'.PHP_EOL; + } + } + }//end if + }//end if + + if (isset($rule->exclude) === true) { + foreach ($rule->exclude as $exclude) { + if (isset($exclude['name']) === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* ignoring empty exclude rule *".PHP_EOL; + echo "\t\t\t=> ".$exclude->asXML().PHP_EOL; + } + + continue; + } + + if ($this->shouldProcessElement($exclude) === false) { + continue; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\tExcluding rule \"".$exclude['name'].'"'.PHP_EOL; + } + + // Check if a single code is being excluded, which is a shortcut + // for setting the severity of the message to 0. + $parts = explode('.', $exclude['name']); + if (count($parts) === 4) { + $this->ruleset[(string) $exclude['name']]['severity'] = 0; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> severity set to 0".PHP_EOL; + } + } else { + $excludedSniffs = array_merge( + $excludedSniffs, + $this->expandRulesetReference((string) $exclude['name'], $rulesetDir, ($depth + 1)) + ); + } + }//end foreach + }//end if + + $this->processRule($rule, $newSniffs, $depth); + }//end foreach + + // Process custom command line arguments. + $cliArgs = []; + foreach ($ruleset->{'arg'} as $arg) { + if ($this->shouldProcessElement($arg) === false) { + continue; + } + + if (isset($arg['name']) === true) { + $argString = '--'.(string) $arg['name']; + if (isset($arg['value']) === true) { + $argString .= '='.(string) $arg['value']; + } + } else { + $argString = '-'.(string) $arg['value']; + } + + $cliArgs[] = $argString; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> set command line value $argString".PHP_EOL; + } + }//end foreach + + // Set custom php ini values as CLI args. + foreach ($ruleset->{'ini'} as $arg) { + if ($this->shouldProcessElement($arg) === false) { + continue; + } + + if (isset($arg['name']) === false) { + continue; + } + + $name = (string) $arg['name']; + $argString = $name; + if (isset($arg['value']) === true) { + $value = (string) $arg['value']; + $argString .= "=$value"; + } else { + $value = 'true'; + } + + $cliArgs[] = '-d'; + $cliArgs[] = $argString; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> set PHP ini value $name to $value".PHP_EOL; + } + }//end foreach + + if (empty($this->config->files) === true) { + // Process hard-coded file paths. + foreach ($ruleset->{'file'} as $file) { + $file = (string) $file; + $cliArgs[] = $file; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> added \"$file\" to the file list".PHP_EOL; + } + } + } + + if (empty($cliArgs) === false) { + // Change the directory so all relative paths are worked + // out based on the location of the ruleset instead of + // the location of the user. + $inPhar = Util\Common::isPharFile($rulesetDir); + if ($inPhar === false) { + $currentDir = getcwd(); + chdir($rulesetDir); + } + + $this->config->setCommandLineValues($cliArgs); + + if ($inPhar === false) { + chdir($currentDir); + } + } + + // Process custom ignore pattern rules. + foreach ($ruleset->{'exclude-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === false) { + continue; + } + + if (isset($pattern['type']) === false) { + $pattern['type'] = 'absolute'; + } + + $this->ignorePatterns[(string) $pattern] = (string) $pattern['type']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t=> added global ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL; + } + } + + $includedSniffs = array_unique(array_merge($ownSniffs, $includedSniffs)); + $excludedSniffs = array_unique($excludedSniffs); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $included = count($includedSniffs); + $excluded = count($excludedSniffs); + echo str_repeat("\t", $depth); + echo "=> Ruleset processing complete; included $included sniffs and excluded $excluded".PHP_EOL; + } + + // Merge our own sniff list with our externally included + // sniff list, but filter out any excluded sniffs. + $files = []; + foreach ($includedSniffs as $sniff) { + if (in_array($sniff, $excludedSniffs, true) === true) { + continue; + } else { + $files[] = Util\Common::realpath($sniff); + } + } + + return $files; + + }//end processRuleset() + + + /** + * Expands a directory into a list of sniff files within. + * + * @param string $directory The path to a directory. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return array + */ + private function expandSniffDirectory($directory, $depth=0) + { + $sniffs = []; + + $rdi = new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS); + $di = new \RecursiveIteratorIterator($rdi, 0, \RecursiveIteratorIterator::CATCH_GET_CHILD); + + $dirLen = strlen($directory); + + foreach ($di as $file) { + $filename = $file->getFilename(); + + // Skip hidden files. + if (substr($filename, 0, 1) === '.') { + continue; + } + + // We are only interested in PHP and sniff files. + $fileParts = explode('.', $filename); + if (array_pop($fileParts) !== 'php') { + continue; + } + + $basename = basename($filename, '.php'); + if (substr($basename, -5) !== 'Sniff') { + continue; + } + + $path = $file->getPathname(); + + // Skip files in hidden directories within the Sniffs directory of this + // standard. We use the offset with strpos() to allow hidden directories + // before, valid example: + // /home/foo/.composer/vendor/squiz/custom_tool/MyStandard/Sniffs/... + if (strpos($path, DIRECTORY_SEPARATOR.'.', $dirLen) !== false) { + continue; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> ".Util\Common::stripBasepath($path, $this->config->basepath).PHP_EOL; + } + + $sniffs[] = $path; + }//end foreach + + return $sniffs; + + }//end expandSniffDirectory() + + + /** + * Expands a ruleset reference into a list of sniff files. + * + * @param string $ref The reference from the ruleset XML file. + * @param string $rulesetDir The directory of the ruleset XML file, used to + * evaluate relative paths. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the reference is invalid. + */ + private function expandRulesetReference($ref, $rulesetDir, $depth=0) + { + // Ignore internal sniffs codes as they are used to only + // hide and change internal messages. + if (substr($ref, 0, 9) === 'Internal.') { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* ignoring internal sniff code *".PHP_EOL; + } + + return []; + } + + // As sniffs can't begin with a full stop, assume references in + // this format are relative paths and attempt to convert them + // to absolute paths. If this fails, let the reference run through + // the normal checks and have it fail as normal. + if (substr($ref, 0, 1) === '.') { + $realpath = Util\Common::realpath($rulesetDir.'/'.$ref); + if ($realpath !== false) { + $ref = $realpath; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL; + } + } + } + + // As sniffs can't begin with a tilde, assume references in + // this format are relative to the user's home directory. + if (substr($ref, 0, 2) === '~/') { + $realpath = Util\Common::realpath($ref); + if ($realpath !== false) { + $ref = $realpath; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL; + } + } + } + + if (is_file($ref) === true) { + if (substr($ref, -9) === 'Sniff.php') { + // A single external sniff. + $this->rulesetDirs[] = dirname(dirname(dirname($ref))); + return [$ref]; + } + } else { + // See if this is a whole standard being referenced. + $path = Util\Standards::getInstalledStandardPath($ref); + if ($path !== null && Util\Common::isPharFile($path) === true && strpos($path, 'ruleset.xml') === false) { + // If the ruleset exists inside the phar file, use it. + if (file_exists($path.DIRECTORY_SEPARATOR.'ruleset.xml') === true) { + $path .= DIRECTORY_SEPARATOR.'ruleset.xml'; + } else { + $path = null; + } + } + + if ($path !== null) { + $ref = $path; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL; + } + } else if (is_dir($ref) === false) { + // Work out the sniff path. + $sepPos = strpos($ref, DIRECTORY_SEPARATOR); + if ($sepPos !== false) { + $stdName = substr($ref, 0, $sepPos); + $path = substr($ref, $sepPos); + } else { + $parts = explode('.', $ref); + $stdName = $parts[0]; + if (count($parts) === 1) { + // A whole standard? + $path = ''; + } else if (count($parts) === 2) { + // A directory of sniffs? + $path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1]; + } else { + // A single sniff? + $path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1].DIRECTORY_SEPARATOR.$parts[2].'Sniff.php'; + } + } + + $newRef = false; + $stdPath = Util\Standards::getInstalledStandardPath($stdName); + if ($stdPath !== null && $path !== '') { + if (Util\Common::isPharFile($stdPath) === true + && strpos($stdPath, 'ruleset.xml') === false + ) { + // Phar files can only return the directory, + // since ruleset can be omitted if building one standard. + $newRef = Util\Common::realpath($stdPath.$path); + } else { + $newRef = Util\Common::realpath(dirname($stdPath).$path); + } + } + + if ($newRef === false) { + // The sniff is not locally installed, so check if it is being + // referenced as a remote sniff outside the install. We do this + // by looking through all directories where we have found ruleset + // files before, looking for ones for this particular standard, + // and seeing if it is in there. + foreach ($this->rulesetDirs as $dir) { + if (strtolower(basename($dir)) !== strtolower($stdName)) { + continue; + } + + $newRef = Util\Common::realpath($dir.$path); + + if ($newRef !== false) { + $ref = $newRef; + } + } + } else { + $ref = $newRef; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL; + } + }//end if + }//end if + + if (is_dir($ref) === true) { + if (is_file($ref.DIRECTORY_SEPARATOR.'ruleset.xml') === true) { + // We are referencing an external coding standard. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* rule is referencing a standard using directory name; processing *".PHP_EOL; + } + + return $this->processRuleset($ref.DIRECTORY_SEPARATOR.'ruleset.xml', ($depth + 2)); + } else { + // We are referencing a whole directory of sniffs. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* rule is referencing a directory of sniffs *".PHP_EOL; + echo str_repeat("\t", $depth); + echo "\t\tAdding sniff files from directory".PHP_EOL; + } + + return $this->expandSniffDirectory($ref, ($depth + 1)); + } + } else { + if (is_file($ref) === false) { + $error = "Referenced sniff \"$ref\" does not exist"; + throw new RuntimeException($error); + } + + if (substr($ref, -9) === 'Sniff.php') { + // A single sniff. + return [$ref]; + } else { + // Assume an external ruleset.xml file. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t* rule is referencing a standard using ruleset path; processing *".PHP_EOL; + } + + return $this->processRuleset($ref, ($depth + 2)); + } + }//end if + + }//end expandRulesetReference() + + + /** + * Processes a rule from a ruleset XML file, overriding built-in defaults. + * + * @param \SimpleXMLElement $rule The rule object from a ruleset XML file. + * @param string[] $newSniffs An array of sniffs that got included by this rule. + * @param int $depth How many nested processing steps we are in. + * This is only used for debug output. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If rule settings are invalid. + */ + private function processRule($rule, $newSniffs, $depth=0) + { + $ref = (string) $rule['ref']; + $todo = [$ref]; + + $parts = explode('.', $ref); + $partsCount = count($parts); + if ($partsCount <= 2 + || $partsCount > count(array_filter($parts)) + || in_array($ref, $newSniffs) === true + ) { + // We are processing a standard, a category of sniffs or a relative path inclusion. + foreach ($newSniffs as $sniffFile) { + $parts = explode(DIRECTORY_SEPARATOR, $sniffFile); + if (count($parts) === 1 && DIRECTORY_SEPARATOR === '\\') { + // Path using forward slashes while running on Windows. + $parts = explode('/', $sniffFile); + } + + $sniffName = array_pop($parts); + $sniffCategory = array_pop($parts); + array_pop($parts); + $sniffStandard = array_pop($parts); + $todo[] = $sniffStandard.'.'.$sniffCategory.'.'.substr($sniffName, 0, -9); + } + } + + foreach ($todo as $code) { + // Custom severity. + if (isset($rule->severity) === true + && $this->shouldProcessElement($rule->severity) === true + ) { + if (isset($this->ruleset[$code]) === false) { + $this->ruleset[$code] = []; + } + + $this->ruleset[$code]['severity'] = (int) $rule->severity; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> severity set to ".(int) $rule->severity; + if ($code !== $ref) { + echo " for $code"; + } + + echo PHP_EOL; + } + } + + // Custom message type. + if (isset($rule->type) === true + && $this->shouldProcessElement($rule->type) === true + ) { + if (isset($this->ruleset[$code]) === false) { + $this->ruleset[$code] = []; + } + + $type = strtolower((string) $rule->type); + if ($type !== 'error' && $type !== 'warning') { + throw new RuntimeException("Message type \"$type\" is invalid; must be \"error\" or \"warning\""); + } + + $this->ruleset[$code]['type'] = $type; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> message type set to ".(string) $rule->type; + if ($code !== $ref) { + echo " for $code"; + } + + echo PHP_EOL; + } + }//end if + + // Custom message. + if (isset($rule->message) === true + && $this->shouldProcessElement($rule->message) === true + ) { + if (isset($this->ruleset[$code]) === false) { + $this->ruleset[$code] = []; + } + + $this->ruleset[$code]['message'] = (string) $rule->message; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> message set to ".(string) $rule->message; + if ($code !== $ref) { + echo " for $code"; + } + + echo PHP_EOL; + } + } + + // Custom properties. + if (isset($rule->properties) === true + && $this->shouldProcessElement($rule->properties) === true + ) { + $propertyScope = 'standard'; + if ($code === $ref || substr($ref, -9) === 'Sniff.php') { + $propertyScope = 'sniff'; + } + + foreach ($rule->properties->property as $prop) { + if ($this->shouldProcessElement($prop) === false) { + continue; + } + + if (isset($this->ruleset[$code]) === false) { + $this->ruleset[$code] = [ + 'properties' => [], + ]; + } else if (isset($this->ruleset[$code]['properties']) === false) { + $this->ruleset[$code]['properties'] = []; + } + + $name = (string) $prop['name']; + if (isset($prop['type']) === true + && (string) $prop['type'] === 'array' + ) { + $values = []; + if (isset($prop['extend']) === true + && (string) $prop['extend'] === 'true' + && isset($this->ruleset[$code]['properties'][$name]['value']) === true + ) { + $values = $this->ruleset[$code]['properties'][$name]['value']; + } + + if (isset($prop->element) === true) { + $printValue = ''; + foreach ($prop->element as $element) { + if ($this->shouldProcessElement($element) === false) { + continue; + } + + $value = (string) $element['value']; + if (isset($element['key']) === true) { + $key = (string) $element['key']; + $values[$key] = $value; + $printValue .= $key.'=>'.$value.','; + } else { + $values[] = $value; + $printValue .= $value.','; + } + } + + $printValue = rtrim($printValue, ','); + } else { + $value = (string) $prop['value']; + $printValue = $value; + foreach (explode(',', $value) as $val) { + list($k, $v) = explode('=>', $val.'=>'); + if ($v !== '') { + $values[trim($k)] = trim($v); + } else { + $values[] = trim($k); + } + } + }//end if + + $this->ruleset[$code]['properties'][$name] = [ + 'value' => $values, + 'scope' => $propertyScope, + ]; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> array property \"$name\" set to \"$printValue\""; + if ($code !== $ref) { + echo " for $code"; + } + + echo PHP_EOL; + } + } else { + $this->ruleset[$code]['properties'][$name] = [ + 'value' => (string) $prop['value'], + 'scope' => $propertyScope, + ]; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> property \"$name\" set to \"".(string) $prop['value'].'"'; + if ($code !== $ref) { + echo " for $code"; + } + + echo PHP_EOL; + } + }//end if + }//end foreach + }//end if + + // Ignore patterns. + foreach ($rule->{'exclude-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === false) { + continue; + } + + if (isset($this->ignorePatterns[$code]) === false) { + $this->ignorePatterns[$code] = []; + } + + if (isset($pattern['type']) === false) { + $pattern['type'] = 'absolute'; + } + + $this->ignorePatterns[$code][(string) $pattern] = (string) $pattern['type']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> added rule-specific ".(string) $pattern['type'].' ignore pattern'; + if ($code !== $ref) { + echo " for $code"; + } + + echo ': '.(string) $pattern.PHP_EOL; + } + }//end foreach + + // Include patterns. + foreach ($rule->{'include-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === false) { + continue; + } + + if (isset($this->includePatterns[$code]) === false) { + $this->includePatterns[$code] = []; + } + + if (isset($pattern['type']) === false) { + $pattern['type'] = 'absolute'; + } + + $this->includePatterns[$code][(string) $pattern] = (string) $pattern['type']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "\t\t=> added rule-specific ".(string) $pattern['type'].' include pattern'; + if ($code !== $ref) { + echo " for $code"; + } + + echo ': '.(string) $pattern.PHP_EOL; + } + }//end foreach + }//end foreach + + }//end processRule() + + + /** + * Determine if an element should be processed or ignored. + * + * @param \SimpleXMLElement $element An object from a ruleset XML file. + * + * @return bool + */ + private function shouldProcessElement($element) + { + if (isset($element['phpcbf-only']) === false + && isset($element['phpcs-only']) === false + ) { + // No exceptions are being made. + return true; + } + + if (PHP_CODESNIFFER_CBF === true + && isset($element['phpcbf-only']) === true + && (string) $element['phpcbf-only'] === 'true' + ) { + return true; + } + + if (PHP_CODESNIFFER_CBF === false + && isset($element['phpcs-only']) === true + && (string) $element['phpcs-only'] === 'true' + ) { + return true; + } + + return false; + + }//end shouldProcessElement() + + + /** + * Loads and stores sniffs objects used for sniffing files. + * + * @param array $files Paths to the sniff files to register. + * @param array $restrictions The sniff class names to restrict the allowed + * listeners to. + * @param array $exclusions The sniff class names to exclude from the + * listeners list. + * + * @return void + */ + public function registerSniffs($files, $restrictions, $exclusions) + { + $listeners = []; + + foreach ($files as $file) { + // Work out where the position of /StandardName/Sniffs/... is + // so we can determine what the class will be called. + $sniffPos = strrpos($file, DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR); + if ($sniffPos === false) { + continue; + } + + $slashPos = strrpos(substr($file, 0, $sniffPos), DIRECTORY_SEPARATOR); + if ($slashPos === false) { + continue; + } + + $className = Autoload::loadFile($file); + $compareName = Util\Common::cleanSniffClass($className); + + // If they have specified a list of sniffs to restrict to, check + // to see if this sniff is allowed. + if (empty($restrictions) === false + && isset($restrictions[$compareName]) === false + ) { + continue; + } + + // If they have specified a list of sniffs to exclude, check + // to see if this sniff is allowed. + if (empty($exclusions) === false + && isset($exclusions[$compareName]) === true + ) { + continue; + } + + // Skip abstract classes. + $reflection = new \ReflectionClass($className); + if ($reflection->isAbstract() === true) { + continue; + } + + $listeners[$className] = $className; + + if (PHP_CODESNIFFER_VERBOSITY > 2) { + echo "Registered $className".PHP_EOL; + } + }//end foreach + + $this->sniffs = $listeners; + + }//end registerSniffs() + + + /** + * Populates the array of PHP_CodeSniffer_Sniff objects for this file. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If sniff registration fails. + */ + public function populateTokenListeners() + { + // Construct a list of listeners indexed by token being listened for. + $this->tokenListeners = []; + + foreach ($this->sniffs as $sniffClass => $sniffObject) { + $this->sniffs[$sniffClass] = null; + $this->sniffs[$sniffClass] = new $sniffClass(); + + $sniffCode = Util\Common::getSniffCode($sniffClass); + $this->sniffCodes[$sniffCode] = $sniffClass; + + // Set custom properties. + if (isset($this->ruleset[$sniffCode]['properties']) === true) { + foreach ($this->ruleset[$sniffCode]['properties'] as $name => $settings) { + $this->setSniffProperty($sniffClass, $name, $settings); + } + } + + $tokenizers = []; + $vars = get_class_vars($sniffClass); + if (isset($vars['supportedTokenizers']) === true) { + foreach ($vars['supportedTokenizers'] as $tokenizer) { + $tokenizers[$tokenizer] = $tokenizer; + } + } else { + $tokenizers = ['PHP' => 'PHP']; + } + + $tokens = $this->sniffs[$sniffClass]->register(); + if (is_array($tokens) === false) { + $msg = "Sniff $sniffClass register() method must return an array"; + throw new RuntimeException($msg); + } + + $ignorePatterns = []; + $patterns = $this->getIgnorePatterns($sniffCode); + foreach ($patterns as $pattern => $type) { + $replacements = [ + '\\,' => ',', + '*' => '.*', + ]; + + $ignorePatterns[] = strtr($pattern, $replacements); + } + + $includePatterns = []; + $patterns = $this->getIncludePatterns($sniffCode); + foreach ($patterns as $pattern => $type) { + $replacements = [ + '\\,' => ',', + '*' => '.*', + ]; + + $includePatterns[] = strtr($pattern, $replacements); + } + + foreach ($tokens as $token) { + if (isset($this->tokenListeners[$token]) === false) { + $this->tokenListeners[$token] = []; + } + + if (isset($this->tokenListeners[$token][$sniffClass]) === false) { + $this->tokenListeners[$token][$sniffClass] = [ + 'class' => $sniffClass, + 'source' => $sniffCode, + 'tokenizers' => $tokenizers, + 'ignore' => $ignorePatterns, + 'include' => $includePatterns, + ]; + } + } + }//end foreach + + }//end populateTokenListeners() + + + /** + * Set a single property for a sniff. + * + * @param string $sniffClass The class name of the sniff. + * @param string $name The name of the property to change. + * @param array $settings Array with the new value of the property and the scope of the property being set. + * + * @return void + * + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException When attempting to set a non-existent property on a sniff + * which doesn't declare the property or explicitly supports + * dynamic properties. + */ + public function setSniffProperty($sniffClass, $name, $settings) + { + // Setting a property for a sniff we are not using. + if (isset($this->sniffs[$sniffClass]) === false) { + return; + } + + $name = trim($name); + $propertyName = $name; + if (substr($propertyName, -2) === '[]') { + $propertyName = substr($propertyName, 0, -2); + } + + /* + * BC-compatibility layer for $settings using the pre-PHPCS 3.8.0 format. + * + * Prior to PHPCS 3.8.0, `$settings` was expected to only contain the new _value_ + * for the property (which could be an array). + * Since PHPCS 3.8.0, `$settings` is expected to be an array with two keys: 'scope' + * and 'value', where 'scope' indicates whether the property should be set to the given 'value' + * for one individual sniff or for all sniffs in a standard. + * + * This BC-layer is only for integrations with PHPCS which may call this method directly + * and will be removed in PHPCS 4.0.0. + */ + + if (is_array($settings) === false + || isset($settings['scope'], $settings['value']) === false + ) { + // This will be an "old" format value. + $settings = [ + 'value' => $settings, + 'scope' => 'standard', + ]; + + trigger_error( + __FUNCTION__.': the format of the $settings parameter has changed from (mixed) $value to array(\'scope\' => \'sniff|standard\', \'value\' => $value). Please update your integration code. See PR #3629 for more information.', + E_USER_DEPRECATED + ); + } + + $isSettable = false; + $sniffObject = $this->sniffs[$sniffClass]; + if (property_exists($sniffObject, $propertyName) === true + || ($sniffObject instanceof stdClass) === true + || method_exists($sniffObject, '__set') === true + ) { + $isSettable = true; + } + + if ($isSettable === false) { + if ($settings['scope'] === 'sniff') { + $notice = "Ruleset invalid. Property \"$propertyName\" does not exist on sniff "; + $notice .= array_search($sniffClass, $this->sniffCodes, true); + throw new RuntimeException($notice); + } + + return; + } + + $value = $settings['value']; + + if (is_string($value) === true) { + $value = trim($value); + } + + if ($value === '') { + $value = null; + } + + // Special case for booleans. + if ($value === 'true') { + $value = true; + } else if ($value === 'false') { + $value = false; + } else if (substr($name, -2) === '[]') { + $name = $propertyName; + $values = []; + if ($value !== null) { + foreach (explode(',', $value) as $val) { + list($k, $v) = explode('=>', $val.'=>'); + if ($v !== '') { + $values[trim($k)] = trim($v); + } else { + $values[] = trim($k); + } + } + } + + $value = $values; + } + + $sniffObject->$name = $value; + + }//end setSniffProperty() + + + /** + * Gets the array of ignore patterns. + * + * Optionally takes a listener to get ignore patterns specified + * for that sniff only. + * + * @param string $listener The listener to get patterns for. If NULL, all + * patterns are returned. + * + * @return array + */ + public function getIgnorePatterns($listener=null) + { + if ($listener === null) { + return $this->ignorePatterns; + } + + if (isset($this->ignorePatterns[$listener]) === true) { + return $this->ignorePatterns[$listener]; + } + + return []; + + }//end getIgnorePatterns() + + + /** + * Gets the array of include patterns. + * + * Optionally takes a listener to get include patterns specified + * for that sniff only. + * + * @param string $listener The listener to get patterns for. If NULL, all + * patterns are returned. + * + * @return array + */ + public function getIncludePatterns($listener=null) + { + if ($listener === null) { + return $this->includePatterns; + } + + if (isset($this->includePatterns[$listener]) === true) { + return $this->includePatterns[$listener]; + } + + return []; + + }//end getIncludePatterns() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Runner.php b/vendor/squizlabs/php_codesniffer/src/Runner.php new file mode 100644 index 0000000..6101387 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Runner.php @@ -0,0 +1,969 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Files\DummyFile; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Files\FileList; +use PHP_CodeSniffer\Util\Cache; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Standards; + +class Runner +{ + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + + /** + * The reporter used for generating reports after the run. + * + * @var \PHP_CodeSniffer\Reporter + */ + public $reporter = null; + + + /** + * Run the PHPCS script. + * + * @return int + */ + public function runPHPCS() + { + $this->registerOutOfMemoryShutdownMessage('phpcs'); + + try { + Util\Timing::startTiming(); + Runner::checkRequirements(); + + if (defined('PHP_CODESNIFFER_CBF') === false) { + define('PHP_CODESNIFFER_CBF', false); + } + + // Creating the Config object populates it with all required settings + // based on the CLI arguments provided to the script and any config + // values the user has set. + $this->config = new Config(); + + // Init the run and load the rulesets to set additional config vars. + $this->init(); + + // Print a list of sniffs in each of the supplied standards. + // We fudge the config here so that each standard is explained in isolation. + if ($this->config->explain === true) { + $standards = $this->config->standards; + foreach ($standards as $standard) { + $this->config->standards = [$standard]; + $ruleset = new Ruleset($this->config); + $ruleset->explain(); + } + + return 0; + } + + // Generate documentation for each of the supplied standards. + if ($this->config->generator !== null) { + $standards = $this->config->standards; + foreach ($standards as $standard) { + $this->config->standards = [$standard]; + $ruleset = new Ruleset($this->config); + $class = 'PHP_CodeSniffer\Generators\\'.$this->config->generator; + $generator = new $class($ruleset); + $generator->generate(); + } + + return 0; + } + + // Other report formats don't really make sense in interactive mode + // so we hard-code the full report here and when outputting. + // We also ensure parallel processing is off because we need to do one file at a time. + if ($this->config->interactive === true) { + $this->config->reports = ['full' => null]; + $this->config->parallel = 1; + $this->config->showProgress = false; + } + + // Disable caching if we are processing STDIN as we can't be 100% + // sure where the file came from or if it will change in the future. + if ($this->config->stdin === true) { + $this->config->cache = false; + } + + $numErrors = $this->run(); + + // Print all the reports for this run. + $toScreen = $this->reporter->printReports(); + + // Only print timer output if no reports were + // printed to the screen so we don't put additional output + // in something like an XML report. If we are printing to screen, + // the report types would have already worked out who should + // print the timer info. + if ($this->config->interactive === false + && ($toScreen === false + || (($this->reporter->totalErrors + $this->reporter->totalWarnings) === 0 && $this->config->showProgress === true)) + ) { + Util\Timing::printRunTime(); + } + } catch (DeepExitException $e) { + echo $e->getMessage(); + return $e->getCode(); + }//end try + + if ($numErrors === 0) { + // No errors found. + return 0; + } else if ($this->reporter->totalFixable === 0) { + // Errors found, but none of them can be fixed by PHPCBF. + return 1; + } else { + // Errors found, and some can be fixed by PHPCBF. + return 2; + } + + }//end runPHPCS() + + + /** + * Run the PHPCBF script. + * + * @return int + */ + public function runPHPCBF() + { + $this->registerOutOfMemoryShutdownMessage('phpcbf'); + + if (defined('PHP_CODESNIFFER_CBF') === false) { + define('PHP_CODESNIFFER_CBF', true); + } + + try { + Util\Timing::startTiming(); + Runner::checkRequirements(); + + // Creating the Config object populates it with all required settings + // based on the CLI arguments provided to the script and any config + // values the user has set. + $this->config = new Config(); + + // When processing STDIN, we can't output anything to the screen + // or it will end up mixed in with the file output. + if ($this->config->stdin === true) { + $this->config->verbosity = 0; + } + + // Init the run and load the rulesets to set additional config vars. + $this->init(); + + // When processing STDIN, we only process one file at a time and + // we don't process all the way through, so we can't use the parallel + // running system. + if ($this->config->stdin === true) { + $this->config->parallel = 1; + } + + // Override some of the command line settings that might break the fixes. + $this->config->generator = null; + $this->config->explain = false; + $this->config->interactive = false; + $this->config->cache = false; + $this->config->showSources = false; + $this->config->recordErrors = false; + $this->config->reportFile = null; + $this->config->reports = ['cbf' => null]; + + // If a standard tries to set command line arguments itself, some + // may be blocked because PHPCBF is running, so stop the script + // dying if any are found. + $this->config->dieOnUnknownArg = false; + + $this->run(); + $this->reporter->printReports(); + + echo PHP_EOL; + Util\Timing::printRunTime(); + } catch (DeepExitException $e) { + echo $e->getMessage(); + return $e->getCode(); + }//end try + + if ($this->reporter->totalFixed === 0) { + // Nothing was fixed by PHPCBF. + if ($this->reporter->totalFixable === 0) { + // Nothing found that could be fixed. + return 0; + } else { + // Something failed to fix. + return 2; + } + } + + if ($this->reporter->totalFixable === 0) { + // PHPCBF fixed all fixable errors. + return 1; + } + + // PHPCBF fixed some fixable errors, but others failed to fix. + return 2; + + }//end runPHPCBF() + + + /** + * Exits if the minimum requirements of PHP_CodeSniffer are not met. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the requirements are not met. + */ + public function checkRequirements() + { + // Check the PHP version. + if (PHP_VERSION_ID < 50400) { + $error = 'ERROR: PHP_CodeSniffer requires PHP version 5.4.0 or greater.'.PHP_EOL; + throw new DeepExitException($error, 3); + } + + $requiredExtensions = [ + 'tokenizer', + 'xmlwriter', + 'SimpleXML', + ]; + $missingExtensions = []; + + foreach ($requiredExtensions as $extension) { + if (extension_loaded($extension) === false) { + $missingExtensions[] = $extension; + } + } + + if (empty($missingExtensions) === false) { + $last = array_pop($requiredExtensions); + $required = implode(', ', $requiredExtensions); + $required .= ' and '.$last; + + if (count($missingExtensions) === 1) { + $missing = $missingExtensions[0]; + } else { + $last = array_pop($missingExtensions); + $missing = implode(', ', $missingExtensions); + $missing .= ' and '.$last; + } + + $error = 'ERROR: PHP_CodeSniffer requires the %s extensions to be enabled. Please enable %s.'.PHP_EOL; + $error = sprintf($error, $required, $missing); + throw new DeepExitException($error, 3); + } + + }//end checkRequirements() + + + /** + * Init the rulesets and other high-level settings. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed. + */ + public function init() + { + if (defined('PHP_CODESNIFFER_CBF') === false) { + define('PHP_CODESNIFFER_CBF', false); + } + + // Ensure this option is enabled or else line endings will not always + // be detected properly for files created on a Mac with the /r line ending. + @ini_set('auto_detect_line_endings', true); + + // Disable the PCRE JIT as this caused issues with parallel running. + ini_set('pcre.jit', false); + + // Check that the standards are valid. + foreach ($this->config->standards as $standard) { + if (Util\Standards::isInstalledStandard($standard) === false) { + // They didn't select a valid coding standard, so help them + // out by letting them know which standards are installed. + $error = 'ERROR: the "'.$standard.'" coding standard is not installed. '; + ob_start(); + Util\Standards::printInstalledStandards(); + $error .= ob_get_contents(); + ob_end_clean(); + throw new DeepExitException($error, 3); + } + } + + // Saves passing the Config object into other objects that only need + // the verbosity flag for debug output. + if (defined('PHP_CODESNIFFER_VERBOSITY') === false) { + define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity); + } + + // Create this class so it is autoloaded and sets up a bunch + // of PHP_CodeSniffer-specific token type constants. + $tokens = new Util\Tokens(); + + // Allow autoloading of custom files inside installed standards. + $installedStandards = Standards::getInstalledStandardDetails(); + foreach ($installedStandards as $name => $details) { + Autoload::addSearchPath($details['path'], $details['namespace']); + } + + // The ruleset contains all the information about how the files + // should be checked and/or fixed. + try { + $this->ruleset = new Ruleset($this->config); + } catch (RuntimeException $e) { + $error = 'ERROR: '.$e->getMessage().PHP_EOL.PHP_EOL; + $error .= $this->config->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + }//end init() + + + /** + * Performs the run. + * + * @return int The number of errors and warnings found. + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException + */ + private function run() + { + // The class that manages all reporters for the run. + $this->reporter = new Reporter($this->config); + + // Include bootstrap files. + foreach ($this->config->bootstrap as $bootstrap) { + include $bootstrap; + } + + if ($this->config->stdin === true) { + $fileContents = $this->config->stdinContent; + if ($fileContents === null) { + $handle = fopen('php://stdin', 'r'); + stream_set_blocking($handle, true); + $fileContents = stream_get_contents($handle); + fclose($handle); + } + + $todo = new FileList($this->config, $this->ruleset); + $dummy = new DummyFile($fileContents, $this->ruleset, $this->config); + $todo->addFile($dummy->path, $dummy); + } else { + if (empty($this->config->files) === true) { + $error = 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL; + $error .= $this->config->printShortUsage(true); + throw new DeepExitException($error, 3); + } + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Creating file list... '; + } + + $todo = new FileList($this->config, $this->ruleset); + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + $numFiles = count($todo); + echo "DONE ($numFiles files in queue)".PHP_EOL; + } + + if ($this->config->cache === true) { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Loading cache... '; + } + + Cache::load($this->ruleset, $this->config); + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + $size = Cache::getSize(); + echo "DONE ($size files in cache)".PHP_EOL; + } + } + }//end if + + // Turn all sniff errors into exceptions. + set_error_handler([$this, 'handleErrors']); + + // If verbosity is too high, turn off parallelism so the + // debug output is clean. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $this->config->parallel = 1; + } + + // If the PCNTL extension isn't installed, we can't fork. + if (function_exists('pcntl_fork') === false) { + $this->config->parallel = 1; + } + + $lastDir = ''; + $numFiles = count($todo); + + if ($this->config->parallel === 1) { + // Running normally. + $numProcessed = 0; + foreach ($todo as $path => $file) { + if ($file->ignored === false) { + $currDir = dirname($path); + if ($lastDir !== $currDir) { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath).PHP_EOL; + } + + $lastDir = $currDir; + } + + $this->processFile($file); + } else if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Skipping '.basename($file->path).PHP_EOL; + } + + $numProcessed++; + $this->printProgress($file, $numFiles, $numProcessed); + } + } else { + // Batching and forking. + $childProcs = []; + $numPerBatch = ceil($numFiles / $this->config->parallel); + + for ($batch = 0; $batch < $this->config->parallel; $batch++) { + $startAt = ($batch * $numPerBatch); + if ($startAt >= $numFiles) { + break; + } + + $endAt = ($startAt + $numPerBatch); + if ($endAt > $numFiles) { + $endAt = $numFiles; + } + + $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child'); + $pid = pcntl_fork(); + if ($pid === -1) { + throw new RuntimeException('Failed to create child process'); + } else if ($pid !== 0) { + $childProcs[$pid] = $childOutFilename; + } else { + // Move forward to the start of the batch. + $todo->rewind(); + for ($i = 0; $i < $startAt; $i++) { + $todo->next(); + } + + // Reset the reporter to make sure only figures from this + // file batch are recorded. + $this->reporter->totalFiles = 0; + $this->reporter->totalErrors = 0; + $this->reporter->totalWarnings = 0; + $this->reporter->totalFixable = 0; + $this->reporter->totalFixed = 0; + + // Process the files. + $pathsProcessed = []; + ob_start(); + for ($i = $startAt; $i < $endAt; $i++) { + $path = $todo->key(); + $file = $todo->current(); + + if ($file->ignored === true) { + $todo->next(); + continue; + } + + $currDir = dirname($path); + if ($lastDir !== $currDir) { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath).PHP_EOL; + } + + $lastDir = $currDir; + } + + $this->processFile($file); + + $pathsProcessed[] = $path; + $todo->next(); + }//end for + + $debugOutput = ob_get_contents(); + ob_end_clean(); + + // Write information about the run to the filesystem + // so it can be picked up by the main process. + $childOutput = [ + 'totalFiles' => $this->reporter->totalFiles, + 'totalErrors' => $this->reporter->totalErrors, + 'totalWarnings' => $this->reporter->totalWarnings, + 'totalFixable' => $this->reporter->totalFixable, + 'totalFixed' => $this->reporter->totalFixed, + ]; + + $output = '<'.'?php'."\n".' $childOutput = '; + $output .= var_export($childOutput, true); + $output .= ";\n\$debugOutput = "; + $output .= var_export($debugOutput, true); + + if ($this->config->cache === true) { + $childCache = []; + foreach ($pathsProcessed as $path) { + $childCache[$path] = Cache::get($path); + } + + $output .= ";\n\$childCache = "; + $output .= var_export($childCache, true); + } + + $output .= ";\n?".'>'; + file_put_contents($childOutFilename, $output); + exit(); + }//end if + }//end for + + $success = $this->processChildProcs($childProcs); + if ($success === false) { + throw new RuntimeException('One or more child processes failed to run'); + } + }//end if + + restore_error_handler(); + + if (PHP_CODESNIFFER_VERBOSITY === 0 + && $this->config->interactive === false + && $this->config->showProgress === true + ) { + echo PHP_EOL.PHP_EOL; + } + + if ($this->config->cache === true) { + Cache::save(); + } + + $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit'); + $ignoreErrors = Config::getConfigData('ignore_errors_on_exit'); + + $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings); + if ($ignoreErrors !== null) { + $ignoreErrors = (bool) $ignoreErrors; + if ($ignoreErrors === true) { + $return -= $this->reporter->totalErrors; + } + } + + if ($ignoreWarnings !== null) { + $ignoreWarnings = (bool) $ignoreWarnings; + if ($ignoreWarnings === true) { + $return -= $this->reporter->totalWarnings; + } + } + + return $return; + + }//end run() + + + /** + * Converts all PHP errors into exceptions. + * + * This method forces a sniff to stop processing if it is not + * able to handle a specific piece of code, instead of continuing + * and potentially getting into a loop. + * + * @param int $code The level of error raised. + * @param string $message The error message. + * @param string $file The path of the file that raised the error. + * @param int $line The line number the error was raised at. + * + * @return bool + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException + */ + public function handleErrors($code, $message, $file, $line) + { + if ((error_reporting() & $code) === 0) { + // This type of error is being muted. + return true; + } + + throw new RuntimeException("$message in $file on line $line"); + + }//end handleErrors() + + + /** + * Processes a single file, including checking and fixing. + * + * @param \PHP_CodeSniffer\Files\File $file The file to be processed. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processFile($file) + { + if (PHP_CODESNIFFER_VERBOSITY > 0) { + $startTime = microtime(true); + echo 'Processing '.basename($file->path).' '; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + } + + try { + $file->process(); + + if (PHP_CODESNIFFER_VERBOSITY > 0) { + $timeTaken = ((microtime(true) - $startTime) * 1000); + if ($timeTaken < 1000) { + $timeTaken = round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = round(($timeTaken / 1000), 2); + echo "DONE in $timeTaken secs"; + } + + if (PHP_CODESNIFFER_CBF === true) { + $errors = $file->getFixableCount(); + echo " ($errors fixable violations)".PHP_EOL; + } else { + $errors = $file->getErrorCount(); + $warnings = $file->getWarningCount(); + echo " ($errors errors, $warnings warnings)".PHP_EOL; + } + } + } catch (\Exception $e) { + $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage(); + + // Determine which sniff caused the error. + $sniffStack = null; + $nextStack = null; + foreach ($e->getTrace() as $step) { + if (isset($step['file']) === false) { + continue; + } + + if (empty($sniffStack) === false) { + $nextStack = $step; + break; + } + + if (substr($step['file'], -9) === 'Sniff.php') { + $sniffStack = $step; + continue; + } + } + + if (empty($sniffStack) === false) { + if (empty($nextStack) === false + && isset($nextStack['class']) === true + && substr($nextStack['class'], -5) === 'Sniff' + ) { + $sniffCode = Common::getSniffCode($nextStack['class']); + } else { + $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1); + } + + $error .= sprintf(PHP_EOL.'The error originated in the %s sniff on line %s.', $sniffCode, $sniffStack['line']); + } + + $file->addErrorOnLine($error, 1, 'Internal.Exception'); + }//end try + + $this->reporter->cacheFileReport($file); + + if ($this->config->interactive === true) { + /* + Running interactively. + Print the error report for the current file and then wait for user input. + */ + + // Get current violations and then clear the list to make sure + // we only print violations for a single file each time. + $numErrors = null; + while ($numErrors !== 0) { + $numErrors = ($file->getErrorCount() + $file->getWarningCount()); + if ($numErrors === 0) { + continue; + } + + $this->reporter->printReport('full'); + + echo ' to recheck, [s] to skip or [q] to quit : '; + $input = fgets(STDIN); + $input = trim($input); + + switch ($input) { + case 's': + break(2); + case 'q': + throw new DeepExitException('', 0); + default: + // Repopulate the sniffs because some of them save their state + // and only clear it when the file changes, but we are rechecking + // the same file. + $file->ruleset->populateTokenListeners(); + $file->reloadContent(); + $file->process(); + $this->reporter->cacheFileReport($file); + break; + } + }//end while + }//end if + + // Clean up the file to save (a lot of) memory. + $file->cleanUp(); + + }//end processFile() + + + /** + * Waits for child processes to complete and cleans up after them. + * + * The reporting information returned by each child process is merged + * into the main reporter class. + * + * @param array $childProcs An array of child processes to wait for. + * + * @return bool + */ + private function processChildProcs($childProcs) + { + $numProcessed = 0; + $totalBatches = count($childProcs); + + $success = true; + + while (count($childProcs) > 0) { + $pid = pcntl_waitpid(0, $status); + if ($pid <= 0) { + continue; + } + + $childProcessStatus = pcntl_wexitstatus($status); + if ($childProcessStatus !== 0) { + $success = false; + } + + $out = $childProcs[$pid]; + unset($childProcs[$pid]); + if (file_exists($out) === false) { + continue; + } + + include $out; + unlink($out); + + $numProcessed++; + + if (isset($childOutput) === false) { + // The child process died, so the run has failed. + $file = new DummyFile('', $this->ruleset, $this->config); + $file->setErrorCounts(1, 0, 0, 0); + $this->printProgress($file, $totalBatches, $numProcessed); + $success = false; + continue; + } + + $this->reporter->totalFiles += $childOutput['totalFiles']; + $this->reporter->totalErrors += $childOutput['totalErrors']; + $this->reporter->totalWarnings += $childOutput['totalWarnings']; + $this->reporter->totalFixable += $childOutput['totalFixable']; + $this->reporter->totalFixed += $childOutput['totalFixed']; + + if (isset($debugOutput) === true) { + echo $debugOutput; + } + + if (isset($childCache) === true) { + foreach ($childCache as $path => $cache) { + Cache::set($path, $cache); + } + } + + // Fake a processed file so we can print progress output for the batch. + $file = new DummyFile('', $this->ruleset, $this->config); + $file->setErrorCounts( + $childOutput['totalErrors'], + $childOutput['totalWarnings'], + $childOutput['totalFixable'], + $childOutput['totalFixed'] + ); + $this->printProgress($file, $totalBatches, $numProcessed); + }//end while + + return $success; + + }//end processChildProcs() + + + /** + * Print progress information for a single processed file. + * + * @param \PHP_CodeSniffer\Files\File $file The file that was processed. + * @param int $numFiles The total number of files to process. + * @param int $numProcessed The number of files that have been processed, + * including this one. + * + * @return void + */ + public function printProgress(File $file, $numFiles, $numProcessed) + { + if (PHP_CODESNIFFER_VERBOSITY > 0 + || $this->config->showProgress === false + ) { + return; + } + + // Show progress information. + if ($file->ignored === true) { + echo 'S'; + } else { + $errors = $file->getErrorCount(); + $warnings = $file->getWarningCount(); + $fixable = $file->getFixableCount(); + $fixed = $file->getFixedCount(); + + if (PHP_CODESNIFFER_CBF === true) { + // Files with fixed errors or warnings are F (green). + // Files with unfixable errors or warnings are E (red). + // Files with no errors or warnings are . (black). + if ($fixable > 0) { + if ($this->config->colors === true) { + echo "\033[31m"; + } + + echo 'E'; + + if ($this->config->colors === true) { + echo "\033[0m"; + } + } else if ($fixed > 0) { + if ($this->config->colors === true) { + echo "\033[32m"; + } + + echo 'F'; + + if ($this->config->colors === true) { + echo "\033[0m"; + } + } else { + echo '.'; + }//end if + } else { + // Files with errors are E (red). + // Files with fixable errors are E (green). + // Files with warnings are W (yellow). + // Files with fixable warnings are W (green). + // Files with no errors or warnings are . (black). + if ($errors > 0) { + if ($this->config->colors === true) { + if ($fixable > 0) { + echo "\033[32m"; + } else { + echo "\033[31m"; + } + } + + echo 'E'; + + if ($this->config->colors === true) { + echo "\033[0m"; + } + } else if ($warnings > 0) { + if ($this->config->colors === true) { + if ($fixable > 0) { + echo "\033[32m"; + } else { + echo "\033[33m"; + } + } + + echo 'W'; + + if ($this->config->colors === true) { + echo "\033[0m"; + } + } else { + echo '.'; + }//end if + }//end if + }//end if + + $numPerLine = 60; + if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) { + return; + } + + $percent = round(($numProcessed / $numFiles) * 100); + $padding = (strlen($numFiles) - strlen($numProcessed)); + if ($numProcessed === $numFiles + && $numFiles > $numPerLine + && ($numProcessed % $numPerLine) !== 0 + ) { + $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine))); + } + + echo str_repeat(' ', $padding)." $numProcessed / $numFiles ($percent%)".PHP_EOL; + + }//end printProgress() + + + /** + * Registers a PHP shutdown function to provide a more informative out of memory error. + * + * @param string $command The command which was used to initiate the PHPCS run. + * + * @return void + */ + private function registerOutOfMemoryShutdownMessage($command) + { + // Allocate all needed memory beforehand as much as possible. + $errorMsg = PHP_EOL.'The PHP_CodeSniffer "%1$s" command ran out of memory.'.PHP_EOL; + $errorMsg .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime'.PHP_EOL; + $errorMsg .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).'.PHP_EOL; + $errorMsg = sprintf($errorMsg, $command); + $memoryError = 'Allowed memory size of'; + $errorArray = [ + 'type' => 42, + 'message' => 'Some random dummy string to take up memory and take up some more memory and some more', + 'file' => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files', + 'line' => 31427, + ]; + + register_shutdown_function( + static function () use ( + $errorMsg, + $memoryError, + $errorArray + ) { + $errorArray = error_get_last(); + if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) { + echo $errorMsg; + } + } + ); + + }//end registerOutOfMemoryShutdownMessage() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php new file mode 100644 index 0000000..95a0a09 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php @@ -0,0 +1,172 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +abstract class AbstractArraySniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + final public function register() + { + return [ + T_ARRAY, + T_OPEN_SHORT_ARRAY, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_ARRAY) { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no'); + + $arrayStart = $tokens[$stackPtr]['parenthesis_opener']; + if (isset($tokens[$arrayStart]['parenthesis_closer']) === false) { + // Incomplete array. + return; + } + + $arrayEnd = $tokens[$arrayStart]['parenthesis_closer']; + } else { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); + $arrayStart = $stackPtr; + $arrayEnd = $tokens[$stackPtr]['bracket_closer']; + } + + $lastContent = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($arrayEnd - 1), null, true); + if ($tokens[$lastContent]['code'] === T_COMMA) { + // Last array item ends with a comma. + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no'); + } + + $indices = []; + + $current = $arrayStart; + while (($next = $phpcsFile->findNext(Tokens::$emptyTokens, ($current + 1), $arrayEnd, true)) !== false) { + $end = $this->getNext($phpcsFile, $next, $arrayEnd); + + if ($tokens[$end]['code'] === T_DOUBLE_ARROW) { + $indexEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($end - 1), null, true); + $valueStart = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + + $indices[] = [ + 'index_start' => $next, + 'index_end' => $indexEnd, + 'arrow' => $end, + 'value_start' => $valueStart, + ]; + } else { + $valueStart = $next; + $indices[] = ['value_start' => $valueStart]; + } + + $current = $this->getNext($phpcsFile, $valueStart, $arrayEnd); + } + + if ($tokens[$arrayStart]['line'] === $tokens[$arrayEnd]['line']) { + $this->processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + } else { + $this->processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + } + + }//end process() + + + /** + * Find next separator in array - either: comma or double arrow. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $ptr The position of current token. + * @param int $arrayEnd The token that ends the array definition. + * + * @return int + */ + private function getNext(File $phpcsFile, $ptr, $arrayEnd) + { + $tokens = $phpcsFile->getTokens(); + + while ($ptr < $arrayEnd) { + if (isset($tokens[$ptr]['scope_closer']) === true) { + $ptr = $tokens[$ptr]['scope_closer']; + } else if (isset($tokens[$ptr]['parenthesis_closer']) === true) { + $ptr = $tokens[$ptr]['parenthesis_closer']; + } else if (isset($tokens[$ptr]['bracket_closer']) === true) { + $ptr = $tokens[$ptr]['bracket_closer']; + } + + if ($tokens[$ptr]['code'] === T_COMMA + || $tokens[$ptr]['code'] === T_DOUBLE_ARROW + ) { + return $ptr; + } + + ++$ptr; + } + + return $ptr; + + }//end getNext() + + + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + abstract protected function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + + + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + abstract protected function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php new file mode 100644 index 0000000..86dc10d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php @@ -0,0 +1,936 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; +use PHP_CodeSniffer\Tokenizers\PHP; +use PHP_CodeSniffer\Exceptions\RuntimeException; + +abstract class AbstractPatternSniff implements Sniff +{ + + /** + * If true, comments will be ignored if they are found in the code. + * + * @var boolean + */ + public $ignoreComments = false; + + /** + * The current file being checked. + * + * @var string + */ + protected $currFile = ''; + + /** + * The parsed patterns array. + * + * @var array + */ + private $parsedPatterns = []; + + /** + * Tokens that this sniff wishes to process outside of the patterns. + * + * @var int[] + * @see registerSupplementary() + * @see processSupplementary() + */ + private $supplementaryTokens = []; + + /** + * Positions in the stack where errors have occurred. + * + * @var array + */ + private $errorPos = []; + + + /** + * Constructs a AbstractPatternSniff. + * + * @param boolean $ignoreComments If true, comments will be ignored. + */ + public function __construct($ignoreComments=null) + { + // This is here for backwards compatibility. + if ($ignoreComments !== null) { + $this->ignoreComments = $ignoreComments; + } + + $this->supplementaryTokens = $this->registerSupplementary(); + + }//end __construct() + + + /** + * Registers the tokens to listen to. + * + * Classes extending AbstractPatternTest should implement the + * getPatterns() method to register the patterns they wish to test. + * + * @return array + * @see process() + */ + final public function register() + { + $listenTypes = []; + $patterns = $this->getPatterns(); + + foreach ($patterns as $pattern) { + $parsedPattern = $this->parse($pattern); + + // Find a token position in the pattern that we can use + // for a listener token. + $pos = $this->getListenerTokenPos($parsedPattern); + $tokenType = $parsedPattern[$pos]['token']; + $listenTypes[] = $tokenType; + + $patternArray = [ + 'listen_pos' => $pos, + 'pattern' => $parsedPattern, + 'pattern_code' => $pattern, + ]; + + if (isset($this->parsedPatterns[$tokenType]) === false) { + $this->parsedPatterns[$tokenType] = []; + } + + $this->parsedPatterns[$tokenType][] = $patternArray; + }//end foreach + + return array_unique(array_merge($listenTypes, $this->supplementaryTokens)); + + }//end register() + + + /** + * Returns the token types that the specified pattern is checking for. + * + * Returned array is in the format: + * + * array( + * T_WHITESPACE => 0, // 0 is the position where the T_WHITESPACE token + * // should occur in the pattern. + * ); + * + * + * @param array $pattern The parsed pattern to find the acquire the token + * types from. + * + * @return array + */ + private function getPatternTokenTypes($pattern) + { + $tokenTypes = []; + foreach ($pattern as $pos => $patternInfo) { + if ($patternInfo['type'] === 'token') { + if (isset($tokenTypes[$patternInfo['token']]) === false) { + $tokenTypes[$patternInfo['token']] = $pos; + } + } + } + + return $tokenTypes; + + }//end getPatternTokenTypes() + + + /** + * Returns the position in the pattern that this test should register as + * a listener for the pattern. + * + * @param array $pattern The pattern to acquire the listener for. + * + * @return int The position in the pattern that this test should register + * as the listener. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If we could not determine a token to listen for. + */ + private function getListenerTokenPos($pattern) + { + $tokenTypes = $this->getPatternTokenTypes($pattern); + $tokenCodes = array_keys($tokenTypes); + $token = Tokens::getHighestWeightedToken($tokenCodes); + + // If we could not get a token. + if ($token === false) { + $error = 'Could not determine a token to listen for'; + throw new RuntimeException($error); + } + + return $tokenTypes[$token]; + + }//end getListenerTokenPos() + + + /** + * Processes the test. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ + final public function process(File $phpcsFile, $stackPtr) + { + $file = $phpcsFile->getFilename(); + if ($this->currFile !== $file) { + // We have changed files, so clean up. + $this->errorPos = []; + $this->currFile = $file; + } + + $tokens = $phpcsFile->getTokens(); + + if (in_array($tokens[$stackPtr]['code'], $this->supplementaryTokens, true) === true) { + $this->processSupplementary($phpcsFile, $stackPtr); + } + + $type = $tokens[$stackPtr]['code']; + + // If the type is not set, then it must have been a token registered + // with registerSupplementary(). + if (isset($this->parsedPatterns[$type]) === false) { + return; + } + + $allErrors = []; + + // Loop over each pattern that is listening to the current token type + // that we are processing. + foreach ($this->parsedPatterns[$type] as $patternInfo) { + // If processPattern returns false, then the pattern that we are + // checking the code with must not be designed to check that code. + $errors = $this->processPattern($patternInfo, $phpcsFile, $stackPtr); + if ($errors === false) { + // The pattern didn't match. + continue; + } else if (empty($errors) === true) { + // The pattern matched, but there were no errors. + break; + } + + foreach ($errors as $stackPtr => $error) { + if (isset($this->errorPos[$stackPtr]) === false) { + $this->errorPos[$stackPtr] = true; + $allErrors[$stackPtr] = $error; + } + } + } + + foreach ($allErrors as $stackPtr => $error) { + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + + }//end process() + + + /** + * Processes the pattern and verifies the code at $stackPtr. + * + * @param array $patternInfo Information about the pattern used + * for checking, which includes are + * parsed token representation of the + * pattern. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack where + * the listening token type was found. + * + * @return array|false + */ + protected function processPattern($patternInfo, File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $pattern = $patternInfo['pattern']; + $patternCode = $patternInfo['pattern_code']; + $errors = []; + $found = ''; + + $ignoreTokens = [T_WHITESPACE => T_WHITESPACE]; + if ($this->ignoreComments === true) { + $ignoreTokens += Tokens::$commentTokens; + } + + $origStackPtr = $stackPtr; + $hasError = false; + + if ($patternInfo['listen_pos'] > 0) { + $stackPtr--; + + for ($i = ($patternInfo['listen_pos'] - 1); $i >= 0; $i--) { + if ($pattern[$i]['type'] === 'token') { + if ($pattern[$i]['token'] === T_WHITESPACE) { + if ($tokens[$stackPtr]['code'] === T_WHITESPACE) { + $found = $tokens[$stackPtr]['content'].$found; + } + + // Only check the size of the whitespace if this is not + // the first token. We don't care about the size of + // leading whitespace, just that there is some. + if ($i !== 0) { + if ($tokens[$stackPtr]['content'] !== $pattern[$i]['value']) { + $hasError = true; + } + } + } else { + // Check to see if this important token is the same as the + // previous important token in the pattern. If it is not, + // then the pattern cannot be for this piece of code. + $prev = $phpcsFile->findPrevious( + $ignoreTokens, + $stackPtr, + null, + true + ); + + if ($prev === false + || $tokens[$prev]['code'] !== $pattern[$i]['token'] + ) { + return false; + } + + // If we skipped past some whitespace tokens, then add them + // to the found string. + $tokenContent = $phpcsFile->getTokensAsString( + ($prev + 1), + ($stackPtr - $prev - 1) + ); + + $found = $tokens[$prev]['content'].$tokenContent.$found; + + if (isset($pattern[($i - 1)]) === true + && $pattern[($i - 1)]['type'] === 'skip' + ) { + $stackPtr = $prev; + } else { + $stackPtr = ($prev - 1); + } + }//end if + } else if ($pattern[$i]['type'] === 'skip') { + // Skip to next piece of relevant code. + if ($pattern[$i]['to'] === 'parenthesis_closer') { + $to = 'parenthesis_opener'; + } else { + $to = 'scope_opener'; + } + + // Find the previous opener. + $next = $phpcsFile->findPrevious( + $ignoreTokens, + $stackPtr, + null, + true + ); + + if ($next === false || isset($tokens[$next][$to]) === false) { + // If there was not opener, then we must be + // using the wrong pattern. + return false; + } + + if ($to === 'parenthesis_opener') { + $found = '{'.$found; + } else { + $found = '('.$found; + } + + $found = '...'.$found; + + // Skip to the opening token. + $stackPtr = ($tokens[$next][$to] - 1); + } else if ($pattern[$i]['type'] === 'string') { + $found = 'abc'; + } else if ($pattern[$i]['type'] === 'newline') { + if ($this->ignoreComments === true + && isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === true + ) { + $startComment = $phpcsFile->findPrevious( + Tokens::$commentTokens, + ($stackPtr - 1), + null, + true + ); + + if ($tokens[$startComment]['line'] !== $tokens[($startComment + 1)]['line']) { + $startComment++; + } + + $tokenContent = $phpcsFile->getTokensAsString( + $startComment, + ($stackPtr - $startComment + 1) + ); + + $found = $tokenContent.$found; + $stackPtr = ($startComment - 1); + } + + if ($tokens[$stackPtr]['code'] === T_WHITESPACE) { + if ($tokens[$stackPtr]['content'] !== $phpcsFile->eolChar) { + $found = $tokens[$stackPtr]['content'].$found; + + // This may just be an indent that comes after a newline + // so check the token before to make sure. If it is a newline, we + // can ignore the error here. + if (($tokens[($stackPtr - 1)]['content'] !== $phpcsFile->eolChar) + && ($this->ignoreComments === true + && isset(Tokens::$commentTokens[$tokens[($stackPtr - 1)]['code']]) === false) + ) { + $hasError = true; + } else { + $stackPtr--; + } + } else { + $found = 'EOL'.$found; + } + } else { + $found = $tokens[$stackPtr]['content'].$found; + $hasError = true; + }//end if + + if ($hasError === false && $pattern[($i - 1)]['type'] !== 'newline') { + // Make sure they only have 1 newline. + $prev = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true); + if ($prev !== false && $tokens[$prev]['line'] !== $tokens[$stackPtr]['line']) { + $hasError = true; + } + } + }//end if + }//end for + }//end if + + $stackPtr = $origStackPtr; + $lastAddedStackPtr = null; + $patternLen = count($pattern); + + for ($i = $patternInfo['listen_pos']; $i < $patternLen; $i++) { + if (isset($tokens[$stackPtr]) === false) { + break; + } + + if ($pattern[$i]['type'] === 'token') { + if ($pattern[$i]['token'] === T_WHITESPACE) { + if ($this->ignoreComments === true) { + // If we are ignoring comments, check to see if this current + // token is a comment. If so skip it. + if (isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === true) { + continue; + } + + // If the next token is a comment, the we need to skip the + // current token as we should allow a space before a + // comment for readability. + if (isset($tokens[($stackPtr + 1)]) === true + && isset(Tokens::$commentTokens[$tokens[($stackPtr + 1)]['code']]) === true + ) { + continue; + } + } + + $tokenContent = ''; + if ($tokens[$stackPtr]['code'] === T_WHITESPACE) { + if (isset($pattern[($i + 1)]) === false) { + // This is the last token in the pattern, so just compare + // the next token of content. + $tokenContent = $tokens[$stackPtr]['content']; + } else { + // Get all the whitespace to the next token. + $next = $phpcsFile->findNext( + Tokens::$emptyTokens, + $stackPtr, + null, + true + ); + + $tokenContent = $phpcsFile->getTokensAsString( + $stackPtr, + ($next - $stackPtr) + ); + + $lastAddedStackPtr = $stackPtr; + $stackPtr = $next; + }//end if + + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $tokenContent; + } + } else { + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $tokens[$stackPtr]['content']; + $lastAddedStackPtr = $stackPtr; + } + }//end if + + if (isset($pattern[($i + 1)]) === true + && $pattern[($i + 1)]['type'] === 'skip' + ) { + // The next token is a skip token, so we just need to make + // sure the whitespace we found has *at least* the + // whitespace required. + if (strpos($tokenContent, $pattern[$i]['value']) !== 0) { + $hasError = true; + } + } else { + if ($tokenContent !== $pattern[$i]['value']) { + $hasError = true; + } + } + } else { + // Check to see if this important token is the same as the + // next important token in the pattern. If it is not, then + // the pattern cannot be for this piece of code. + $next = $phpcsFile->findNext( + $ignoreTokens, + $stackPtr, + null, + true + ); + + if ($next === false + || $tokens[$next]['code'] !== $pattern[$i]['token'] + ) { + // The next important token did not match the pattern. + return false; + } + + if ($lastAddedStackPtr !== null) { + if (($tokens[$next]['code'] === T_OPEN_CURLY_BRACKET + || $tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) + && isset($tokens[$next]['scope_condition']) === true + && $tokens[$next]['scope_condition'] > $lastAddedStackPtr + ) { + // This is a brace, but the owner of it is after the current + // token, which means it does not belong to any token in + // our pattern. This means the pattern is not for us. + return false; + } + + if (($tokens[$next]['code'] === T_OPEN_PARENTHESIS + || $tokens[$next]['code'] === T_CLOSE_PARENTHESIS) + && isset($tokens[$next]['parenthesis_owner']) === true + && $tokens[$next]['parenthesis_owner'] > $lastAddedStackPtr + ) { + // This is a bracket, but the owner of it is after the current + // token, which means it does not belong to any token in + // our pattern. This means the pattern is not for us. + return false; + } + }//end if + + // If we skipped past some whitespace tokens, then add them + // to the found string. + if (($next - $stackPtr) > 0) { + $hasComment = false; + for ($j = $stackPtr; $j < $next; $j++) { + $found .= $tokens[$j]['content']; + if (isset(Tokens::$commentTokens[$tokens[$j]['code']]) === true) { + $hasComment = true; + } + } + + // If we are not ignoring comments, this additional + // whitespace or comment is not allowed. If we are + // ignoring comments, there needs to be at least one + // comment for this to be allowed. + if ($this->ignoreComments === false + || ($this->ignoreComments === true + && $hasComment === false) + ) { + $hasError = true; + } + + // Even when ignoring comments, we are not allowed to include + // newlines without the pattern specifying them, so + // everything should be on the same line. + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + $hasError = true; + } + }//end if + + if ($next !== $lastAddedStackPtr) { + $found .= $tokens[$next]['content']; + $lastAddedStackPtr = $next; + } + + if (isset($pattern[($i + 1)]) === true + && $pattern[($i + 1)]['type'] === 'skip' + ) { + $stackPtr = $next; + } else { + $stackPtr = ($next + 1); + } + }//end if + } else if ($pattern[$i]['type'] === 'skip') { + if ($pattern[$i]['to'] === 'unknown') { + $next = $phpcsFile->findNext( + $pattern[($i + 1)]['token'], + $stackPtr + ); + + if ($next === false) { + // Couldn't find the next token, so we must + // be using the wrong pattern. + return false; + } + + $found .= '...'; + $stackPtr = $next; + } else { + // Find the previous opener. + $next = $phpcsFile->findPrevious( + Tokens::$blockOpeners, + $stackPtr + ); + + if ($next === false + || isset($tokens[$next][$pattern[$i]['to']]) === false + ) { + // If there was not opener, then we must + // be using the wrong pattern. + return false; + } + + $found .= '...'; + if ($pattern[$i]['to'] === 'parenthesis_closer') { + $found .= ')'; + } else { + $found .= '}'; + } + + // Skip to the closing token. + $stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1); + }//end if + } else if ($pattern[$i]['type'] === 'string') { + if ($tokens[$stackPtr]['code'] !== T_STRING) { + $hasError = true; + } + + if ($stackPtr !== $lastAddedStackPtr) { + $found .= 'abc'; + $lastAddedStackPtr = $stackPtr; + } + + $stackPtr++; + } else if ($pattern[$i]['type'] === 'newline') { + // Find the next token that contains a newline character. + $newline = 0; + for ($j = $stackPtr; $j < $phpcsFile->numTokens; $j++) { + if (strpos($tokens[$j]['content'], $phpcsFile->eolChar) !== false) { + $newline = $j; + break; + } + } + + if ($newline === 0) { + // We didn't find a newline character in the rest of the file. + $next = ($phpcsFile->numTokens - 1); + $hasError = true; + } else { + if ($this->ignoreComments === false) { + // The newline character cannot be part of a comment. + if (isset(Tokens::$commentTokens[$tokens[$newline]['code']]) === true) { + $hasError = true; + } + } + + if ($newline === $stackPtr) { + $next = ($stackPtr + 1); + } else { + // Check that there were no significant tokens that we + // skipped over to find our newline character. + $next = $phpcsFile->findNext( + $ignoreTokens, + $stackPtr, + null, + true + ); + + if ($next < $newline) { + // We skipped a non-ignored token. + $hasError = true; + } else { + $next = ($newline + 1); + } + } + }//end if + + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $phpcsFile->getTokensAsString( + $stackPtr, + ($next - $stackPtr) + ); + + $lastAddedStackPtr = ($next - 1); + } + + $stackPtr = $next; + }//end if + }//end for + + if ($hasError === true) { + $error = $this->prepareError($found, $patternCode); + $errors[$origStackPtr] = $error; + } + + return $errors; + + }//end processPattern() + + + /** + * Prepares an error for the specified patternCode. + * + * @param string $found The actual found string in the code. + * @param string $patternCode The expected pattern code. + * + * @return string The error message. + */ + protected function prepareError($found, $patternCode) + { + $found = str_replace("\r\n", '\n', $found); + $found = str_replace("\n", '\n', $found); + $found = str_replace("\r", '\n', $found); + $found = str_replace("\t", '\t', $found); + $found = str_replace('EOL', '\n', $found); + $expected = str_replace('EOL', '\n', $patternCode); + + $error = "Expected \"$expected\"; found \"$found\""; + + return $error; + + }//end prepareError() + + + /** + * Returns the patterns that should be checked. + * + * @return string[] + */ + abstract protected function getPatterns(); + + + /** + * Registers any supplementary tokens that this test might wish to process. + * + * A sniff may wish to register supplementary tests when it wishes to group + * an arbitrary validation that cannot be performed using a pattern, with + * other pattern tests. + * + * @return int[] + * @see processSupplementary() + */ + protected function registerSupplementary() + { + return []; + + }//end registerSupplementary() + + + /** + * Processes any tokens registered with registerSupplementary(). + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where to + * process the skip. + * @param int $stackPtr The position in the tokens stack to + * process. + * + * @return void + * @see registerSupplementary() + */ + protected function processSupplementary(File $phpcsFile, $stackPtr) + { + + }//end processSupplementary() + + + /** + * Parses a pattern string into an array of pattern steps. + * + * @param string $pattern The pattern to parse. + * + * @return array The parsed pattern array. + * @see createSkipPattern() + * @see createTokenPattern() + */ + private function parse($pattern) + { + $patterns = []; + $length = strlen($pattern); + $lastToken = 0; + $firstToken = 0; + + for ($i = 0; $i < $length; $i++) { + $specialPattern = false; + $isLastChar = ($i === ($length - 1)); + $oldFirstToken = $firstToken; + + if (substr($pattern, $i, 3) === '...') { + // It's a skip pattern. The skip pattern requires the + // content of the token in the "from" position and the token + // to skip to. + $specialPattern = $this->createSkipPattern($pattern, ($i - 1)); + $lastToken = ($i - $firstToken); + $firstToken = ($i + 3); + $i += 2; + + if ($specialPattern['to'] !== 'unknown') { + $firstToken++; + } + } else if (substr($pattern, $i, 3) === 'abc') { + $specialPattern = ['type' => 'string']; + $lastToken = ($i - $firstToken); + $firstToken = ($i + 3); + $i += 2; + } else if (substr($pattern, $i, 3) === 'EOL') { + $specialPattern = ['type' => 'newline']; + $lastToken = ($i - $firstToken); + $firstToken = ($i + 3); + $i += 2; + }//end if + + if ($specialPattern !== false || $isLastChar === true) { + // If we are at the end of the string, don't worry about a limit. + if ($isLastChar === true) { + // Get the string from the end of the last skip pattern, if any, + // to the end of the pattern string. + $str = substr($pattern, $oldFirstToken); + } else { + // Get the string from the end of the last special pattern, + // if any, to the start of this special pattern. + if ($lastToken === 0) { + // Note that if the last special token was zero characters ago, + // there will be nothing to process so we can skip this bit. + // This happens if you have something like: EOL... in your pattern. + $str = ''; + } else { + $str = substr($pattern, $oldFirstToken, $lastToken); + } + } + + if ($str !== '') { + $tokenPatterns = $this->createTokenPattern($str); + foreach ($tokenPatterns as $tokenPattern) { + $patterns[] = $tokenPattern; + } + } + + // Make sure we don't skip the last token. + if ($isLastChar === false && $i === ($length - 1)) { + $i--; + } + }//end if + + // Add the skip pattern *after* we have processed + // all the tokens from the end of the last skip pattern + // to the start of this skip pattern. + if ($specialPattern !== false) { + $patterns[] = $specialPattern; + } + }//end for + + return $patterns; + + }//end parse() + + + /** + * Creates a skip pattern. + * + * @param string $pattern The pattern being parsed. + * @param int $from The token position that the skip pattern starts from. + * + * @return array The pattern step. + * @see createTokenPattern() + * @see parse() + */ + private function createSkipPattern($pattern, $from) + { + $skip = ['type' => 'skip']; + + $nestedParenthesis = 0; + $nestedBraces = 0; + for ($start = $from; $start >= 0; $start--) { + switch ($pattern[$start]) { + case '(': + if ($nestedParenthesis === 0) { + $skip['to'] = 'parenthesis_closer'; + } + + $nestedParenthesis--; + break; + case '{': + if ($nestedBraces === 0) { + $skip['to'] = 'scope_closer'; + } + + $nestedBraces--; + break; + case '}': + $nestedBraces++; + break; + case ')': + $nestedParenthesis++; + break; + }//end switch + + if (isset($skip['to']) === true) { + break; + } + }//end for + + if (isset($skip['to']) === false) { + $skip['to'] = 'unknown'; + } + + return $skip; + + }//end createSkipPattern() + + + /** + * Creates a token pattern. + * + * @param string $str The tokens string that the pattern should match. + * + * @return array The pattern step. + * @see createSkipPattern() + * @see parse() + */ + private function createTokenPattern($str) + { + // Don't add a space after the closing php tag as it will add a new + // whitespace token. + $tokenizer = new PHP('', null); + + // Remove the getTokens(); + $tokens = array_slice($tokens, 1, (count($tokens) - 2)); + + $patterns = []; + foreach ($tokens as $patternInfo) { + $patterns[] = [ + 'type' => 'token', + 'token' => $patternInfo['code'], + 'value' => $patternInfo['content'], + ]; + } + + return $patterns; + + }//end createTokenPattern() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php new file mode 100644 index 0000000..74201ab --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php @@ -0,0 +1,189 @@ + + * class ClassScopeTest extends PHP_CodeSniffer_Standards_AbstractScopeSniff + * { + * public function __construct() + * { + * parent::__construct(array(T_CLASS), array(T_FUNCTION)); + * } + * + * protected function processTokenWithinScope(\PHP_CodeSniffer\Files\File $phpcsFile, $stackPtr, $currScope) + * { + * $className = $phpcsFile->getDeclarationName($currScope); + * echo 'encountered a method within class '.$className; + * } + * } + * + * + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Exceptions\RuntimeException; + +abstract class AbstractScopeSniff implements Sniff +{ + + /** + * The token types that this test wishes to listen to within the scope. + * + * @var array + */ + private $tokens = []; + + /** + * The type of scope opener tokens that this test wishes to listen to. + * + * @var array + */ + private $scopeTokens = []; + + /** + * True if this test should fire on tokens outside of the scope. + * + * @var boolean + */ + private $listenOutside = false; + + + /** + * Constructs a new AbstractScopeTest. + * + * @param array $scopeTokens The type of scope the test wishes to listen to. + * @param array $tokens The tokens that the test wishes to listen to + * within the scope. + * @param boolean $listenOutside If true this test will also alert the + * extending class when a token is found outside + * the scope, by calling the + * processTokenOutsideScope method. + * + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified tokens arrays are empty + * or invalid. + */ + public function __construct( + array $scopeTokens, + array $tokens, + $listenOutside=false + ) { + if (empty($scopeTokens) === true) { + $error = 'The scope tokens list cannot be empty'; + throw new RuntimeException($error); + } + + if (empty($tokens) === true) { + $error = 'The tokens list cannot be empty'; + throw new RuntimeException($error); + } + + $invalidScopeTokens = array_intersect($scopeTokens, $tokens); + if (empty($invalidScopeTokens) === false) { + $invalid = implode(', ', $invalidScopeTokens); + $error = "Scope tokens [$invalid] can't be in the tokens array"; + throw new RuntimeException($error); + } + + $this->listenOutside = $listenOutside; + $this->scopeTokens = array_flip($scopeTokens); + $this->tokens = $tokens; + + }//end __construct() + + + /** + * The method that is called to register the tokens this test wishes to + * listen to. + * + * DO NOT OVERRIDE THIS METHOD. Use the constructor of this class to register + * for the desired tokens and scope. + * + * @return array + * @see __constructor() + */ + final public function register() + { + return $this->tokens; + + }//end register() + + + /** + * Processes the tokens that this test is listening for. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + * @see processTokenWithinScope() + */ + final public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $foundScope = false; + $skipTokens = []; + foreach ($tokens[$stackPtr]['conditions'] as $scope => $code) { + if (isset($this->scopeTokens[$code]) === true) { + $skipTokens[] = $this->processTokenWithinScope($phpcsFile, $stackPtr, $scope); + $foundScope = true; + } + } + + if ($this->listenOutside === true && $foundScope === false) { + $skipTokens[] = $this->processTokenOutsideScope($phpcsFile, $stackPtr); + } + + if (empty($skipTokens) === false) { + return min($skipTokens); + } + + }//end process() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * @param int $currScope The position in the tokens array that + * opened the scope that this test is + * listening for. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + abstract protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope); + + + /** + * Processes a token that is found outside the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return (count($tokens) + 1) to skip + * the rest of the file. + */ + abstract protected function processTokenOutsideScope(File $phpcsFile, $stackPtr); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php new file mode 100644 index 0000000..6493d57 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php @@ -0,0 +1,230 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +abstract class AbstractVariableSniff extends AbstractScopeSniff +{ + + /** + * List of PHP Reserved variables. + * + * Used by various naming convention sniffs. + * + * @var array + */ + protected $phpReservedVars = [ + '_SERVER' => true, + '_GET' => true, + '_POST' => true, + '_REQUEST' => true, + '_SESSION' => true, + '_ENV' => true, + '_COOKIE' => true, + '_FILES' => true, + 'GLOBALS' => true, + 'http_response_header' => true, + 'HTTP_RAW_POST_DATA' => true, + 'php_errormsg' => true, + ]; + + + /** + * Constructs an AbstractVariableTest. + */ + public function __construct() + { + $scopes = Tokens::$ooScopeTokens; + + $listen = [ + T_VARIABLE, + T_DOUBLE_QUOTED_STRING, + T_HEREDOC, + ]; + + parent::__construct($scopes, $listen, true); + + }//end __construct() + + + /** + * Processes the token in the specified PHP_CodeSniffer\Files\File. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * @param int $currScope The current scope opener token. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + final protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING + || $tokens[$stackPtr]['code'] === T_HEREDOC + ) { + // Check to see if this string has a variable in it. + $pattern = '|(?processVariableInString($phpcsFile, $stackPtr); + } + + return; + } + + // If this token is nested inside a function at a deeper + // level than the current OO scope that was found, it's a normal + // variable and not a member var. + $conditions = array_reverse($tokens[$stackPtr]['conditions'], true); + $inFunction = false; + foreach ($conditions as $scope => $code) { + if (isset(Tokens::$ooScopeTokens[$code]) === true) { + break; + } + + if ($code === T_FUNCTION || $code === T_CLOSURE) { + $inFunction = true; + } + } + + if ($scope !== $currScope) { + // We found a closer scope to this token, so ignore + // this particular time through the sniff. We will process + // this token when this closer scope is found to avoid + // duplicate checks. + return; + } + + // Just make sure this isn't a variable in a function declaration. + if ($inFunction === false && isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $opener => $closer) { + if (isset($tokens[$opener]['parenthesis_owner']) === false) { + // Check if this is a USE statement for a closure. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($opener - 1), null, true); + if ($tokens[$prev]['code'] === T_USE) { + $inFunction = true; + break; + } + + continue; + } + + $owner = $tokens[$opener]['parenthesis_owner']; + if ($tokens[$owner]['code'] === T_FUNCTION + || $tokens[$owner]['code'] === T_CLOSURE + ) { + $inFunction = true; + break; + } + } + }//end if + + if ($inFunction === true) { + return $this->processVariable($phpcsFile, $stackPtr); + } else { + return $this->processMemberVar($phpcsFile, $stackPtr); + } + + }//end processTokenWithinScope() + + + /** + * Processes the token outside the scope in the file. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + final protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + // These variables are not member vars. + if ($tokens[$stackPtr]['code'] === T_VARIABLE) { + return $this->processVariable($phpcsFile, $stackPtr); + } else if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING + || $tokens[$stackPtr]['code'] === T_HEREDOC + ) { + // Check to see if this string has a variable in it. + $pattern = '|(?processVariableInString($phpcsFile, $stackPtr); + } + } + + }//end processTokenOutsideScope() + + + /** + * Called to process class member vars. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + abstract protected function processMemberVar(File $phpcsFile, $stackPtr); + + + /** + * Called to process normal member vars. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + abstract protected function processVariable(File $phpcsFile, $stackPtr); + + + /** + * Called to process variables found in double quoted strings or heredocs. + * + * Note that there may be more than one variable in the string, which will + * result only in one call for the string or one call per line for heredocs. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the double quoted + * string was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + abstract protected function processVariableInString(File $phpcsFile, $stackPtr); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php new file mode 100644 index 0000000..3556edd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; + +interface Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * An example return value for a sniff that wants to listen for whitespace + * and any comments would be: + * + * + * return array( + * T_WHITESPACE, + * T_DOC_COMMENT, + * T_COMMENT, + * ); + * + * + * @return array + * @see Tokens.php + */ + public function register(); + + + /** + * Called when one of the token types that this sniff is listening for + * is found. + * + * The stackPtr variable indicates where in the stack the token was found. + * A sniff can acquire information about this token, along with all the other + * tokens within the stack by first acquiring the token stack: + * + * + * $tokens = $phpcsFile->getTokens(); + * echo 'Encountered a '.$tokens[$stackPtr]['type'].' token'; + * echo 'token information: '; + * print_r($tokens[$stackPtr]); + * + * + * If the sniff discovers an anomaly in the code, they can raise an error + * by calling addError() on the \PHP_CodeSniffer\Files\File object, specifying an error + * message and the position of the offending token: + * + * + * $phpcsFile->addError('Encountered an error', $stackPtr); + * + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token was found. + * @param int $stackPtr The position in the PHP_CodeSniffer + * file's token stack where the token + * was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return (count($tokens) + 1) to skip + * the rest of the file. + */ + public function process(File $phpcsFile, $stackPtr); + + +}//end interface diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml new file mode 100644 index 0000000..21b0d27 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml @@ -0,0 +1,23 @@ + + + + + + + [ + 'foo' => 'bar', +]; + ]]> + + + array( + 'foo' => 'bar', +); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml new file mode 100644 index 0000000..f24767c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml @@ -0,0 +1,23 @@ + + + + + + + array( + 'foo' => 'bar', +); + ]]> + + + [ + 'foo' => 'bar', +]; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml new file mode 100644 index 0000000..4b0ec96 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml @@ -0,0 +1,27 @@ + + + + + + + Foo +{ +} + ]]> + + + Foo +{ +} + +class Foo +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml new file mode 100644 index 0000000..6fa08be --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml @@ -0,0 +1,36 @@ + + + + + + + { +} + ]]> + + + { +} + ]]> + + + + + { +} + ]]> + + + // Start of class. +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml new file mode 100644 index 0000000..9961ea0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $test === 'abc') { + // Code. +} + ]]> + + + $test = 'abc') { + // Code. +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyPHPStatementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyPHPStatementStandard.xml new file mode 100644 index 0000000..5652f65 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyPHPStatementStandard.xml @@ -0,0 +1,44 @@ + + + + + + + echo 'Hello World'; ?> +'Hello World'; ?> + ]]> + + + ; ?> + ?> + ]]> + + + + + + + + ; +if (true) { + echo 'Hello World'; +} + ]]> + + + ;;; +if (true) { + echo 'Hello World'; +}; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml new file mode 100644 index 0000000..c400d75 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + // do nothing +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml new file mode 100644 index 0000000..06f0b7a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $i = 0; $i < 10; $i++) { + echo "{$i}\n"; +} + ]]> + + + ;$test;) { + $test = doSomething(); +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml new file mode 100644 index 0000000..f40d94b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml @@ -0,0 +1,24 @@ + + + + + + + $end = count($foo); +for ($i = 0; $i < $end; $i++) { + echo $foo[$i]."\n"; +} + ]]> + + + count($foo); $i++) { + echo $foo[$i]."\n"; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml new file mode 100644 index 0000000..50f0782 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $i++) { + for ($j = 0; $j < 10; $j++) { + } +} + ]]> + + + $i++) { + for ($j = 0; $j < 10; $i++) { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml new file mode 100644 index 0000000..b2eaabe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml @@ -0,0 +1,39 @@ + + + + + + + $test) { + $var = 1; +} + ]]> + + + true) { + $var = 1; +} + ]]> + + + + + $test) { + $var = 1; +} + ]]> + + + false) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml new file mode 100644 index 0000000..8936740 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml @@ -0,0 +1,29 @@ + + + + + + + + + + final function bar() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml new file mode 100644 index 0000000..181dff4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $a + $b + $c; +} + ]]> + + + $a + $b; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml new file mode 100644 index 0000000..ba8bd7e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml @@ -0,0 +1,32 @@ + + + + + + + $this->doSomethingElse(); + } +} + ]]> + + + parent::bar(); + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml new file mode 100644 index 0000000..174c6b0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml @@ -0,0 +1,25 @@ + + + + + + + Handle strange case +if ($test) { + $var = 1; +} + ]]> + + + FIXME: This needs to be fixed! +if ($test) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml new file mode 100644 index 0000000..c9c4fc0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml @@ -0,0 +1,25 @@ + + + + + + + Handle strange case +if ($test) { + $var = 1; +} + ]]> + + + TODO: This needs to be fixed! +if ($test) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml new file mode 100644 index 0000000..570e419 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml @@ -0,0 +1,23 @@ + + + + + + + { + $var = 1; +} + ]]> + + + { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml new file mode 100644 index 0000000..06ae14b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml @@ -0,0 +1,22 @@ + + + + + + + { + $var = 1; +} + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml new file mode 100644 index 0000000..b57a970 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml @@ -0,0 +1,19 @@ + + + + + + + %; } + ]]> + + + %; } + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml new file mode 100644 index 0000000..9df9aec --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml @@ -0,0 +1,19 @@ + + + + + + + ]; + ]]> + + + ,]; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml new file mode 100644 index 0000000..7525e9e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml @@ -0,0 +1,19 @@ + + + + + + + var foo = 5; + ]]> + + + foo = 5; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml new file mode 100644 index 0000000..88591f9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml new file mode 100644 index 0000000..aa757ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml new file mode 100644 index 0000000..227d562 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml new file mode 100644 index 0000000..6114f24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml new file mode 100644 index 0000000..3fbf502 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml @@ -0,0 +1,24 @@ + + + + + + + + + + some string here + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml new file mode 100644 index 0000000..4554d0f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml new file mode 100644 index 0000000..31342e3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml new file mode 100644 index 0000000..a1be34c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml new file mode 100644 index 0000000..7b58576 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + class Foo +{ +} + ]]> + + + class Foo +{ +} + +class Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml new file mode 100644 index 0000000..de97531 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + interface Foo +{ +} + ]]> + + + interface Foo +{ +} + +interface Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml new file mode 100644 index 0000000..4d957e7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + trait Foo +{ +} + ]]> + + + trait Foo +{ +} + +class Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml new file mode 100644 index 0000000..58a6482 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + trait Foo +{ +} + ]]> + + + trait Foo +{ +} + +trait Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml new file mode 100644 index 0000000..f0d4490 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml new file mode 100644 index 0000000..4c33d76 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml @@ -0,0 +1,56 @@ + + + + + + + = (1 + 2); +$veryLongVarName = 'string'; +$var = foo($bar, $baz); + ]]> + + + = (1 + 2); +$veryLongVarName = 'string'; +$var = foo($bar, $baz); + ]]> + + + + + + + + += 1; +$veryLongVarName = 1; + ]]> + + + += 1; +$veryLongVarName = 1; + ]]> + + + + + = 1; +$veryLongVarName -= 1; + ]]> + + + = 1; +$veryLongVarName -= 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml new file mode 100644 index 0000000..042e4f8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml new file mode 100644 index 0000000..75eba77 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml @@ -0,0 +1,19 @@ + + + + + + + 1; + ]]> + + + 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml new file mode 100644 index 0000000..aea8636 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml @@ -0,0 +1,22 @@ + + + + + + + $someVar || ! $x instanceOf stdClass) {}; + ]]> + + + $someVar || !$x instanceOf stdClass) {}; + +if (! $someVar || ! + $x instanceOf stdClass) {}; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceBeforeCastStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceBeforeCastStandard.xml new file mode 100644 index 0000000..09fbc18 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceBeforeCastStandard.xml @@ -0,0 +1,21 @@ + + + + + + + (int) $string; +$c = $a . (string) $b; + ]]> + + + (int) $string; +$c = $a . (string) $b; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml new file mode 100644 index 0000000..738998d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml @@ -0,0 +1,31 @@ + + + + + + + &$bar) +{ + $bar++; +} + +$baz = 1; +foo($baz); + ]]> + + + &$baz); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml new file mode 100644 index 0000000..9809844 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml @@ -0,0 +1,39 @@ + + + + + + + $baz) +{ +} + ]]> + + + $baz) +{ +} + ]]> + + + + + = true) +{ +} + ]]> + + + =true) +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml new file mode 100644 index 0000000..414dc28 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml @@ -0,0 +1,24 @@ + + + + + + + { + ... +} + ]]> + + + { + ... +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml new file mode 100644 index 0000000..84c2bdd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml @@ -0,0 +1,24 @@ + + + + + + + { + ... +} + ]]> + + + { + ... +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml new file mode 100644 index 0000000..a928e7d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml new file mode 100644 index 0000000..f66cd92 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml new file mode 100644 index 0000000..c30d26e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + AbstractBar +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml new file mode 100644 index 0000000..f5345b7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml @@ -0,0 +1,23 @@ + + + + + + + doSomething() +{ +} + ]]> + + + do_something() +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml new file mode 100644 index 0000000..9dfc175 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + __construct() + { + } +} + ]]> + + + Foo() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml new file mode 100644 index 0000000..0aa0c76 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + BarInterface +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml new file mode 100644 index 0000000..711867e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + BarTrait +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml new file mode 100644 index 0000000..6ef61b9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + FOO_CONSTANT', 'foo'); + +class FooClass +{ + const FOO_CONSTANT = 'foo'; +} + ]]> + + + Foo_Constant', 'foo'); + +class FooClass +{ + const foo_constant = 'foo'; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml new file mode 100644 index 0000000..4ebd677 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml new file mode 100644 index 0000000..df5a0eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml @@ -0,0 +1,22 @@ + + + + + + + + + + Beginning content + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml new file mode 100644 index 0000000..09afb2d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml @@ -0,0 +1,22 @@ + + + + + + + +echo 'Foo'; +?> + ]]> + + + +echo 'Foo'; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml new file mode 100644 index 0000000..33b803a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + explode('a', $bar); + ]]> + + + split('a', $bar); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml new file mode 100644 index 0000000..bdfd5dc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml @@ -0,0 +1,7 @@ + + + to delimit PHP code, do not use the ASP <% %> style tags nor the tags. This is the most portable way to include PHP code on differing operating systems and setups. + ]]> + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml new file mode 100644 index 0000000..f947694 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml new file mode 100644 index 0000000..8086ea2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml @@ -0,0 +1,7 @@ + + + to delimit PHP code, not the shorthand. This is the most portable way to include PHP code on differing operating systems and setups. + ]]> + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml new file mode 100644 index 0000000..83bceef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml new file mode 100644 index 0000000..c0f18b5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + count($bar); + ]]> + + + sizeof($bar); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml new file mode 100644 index 0000000..7dc30c1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml @@ -0,0 +1,23 @@ + + + true, false and null constants must always be lowercase. + ]]> + + + + false || $var === null) { + $var = true; +} + ]]> + + + FALSE || $var === NULL) { + $var = TRUE; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml new file mode 100644 index 0000000..965742d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml @@ -0,0 +1,19 @@ + + + + + + + array(); + ]]> + + + Array(); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml new file mode 100644 index 0000000..f38df3a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml @@ -0,0 +1,38 @@ + + + + + + + + + + Int $foo) : STRING { +} + ]]> + + + + + + + + + + + (BOOL) $isValid; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml new file mode 100644 index 0000000..df69887 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml @@ -0,0 +1,23 @@ + + + + + + + isset($foo) && $foo) { + echo "Hello\n"; +} + ]]> + + + @$foo) { + echo "Hello\n"; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml new file mode 100644 index 0000000..e74005a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml @@ -0,0 +1,23 @@ + + + + + + + PHP_SAPI === 'cli') { + echo "Hello, CLI user."; +} + ]]> + + + php_sapi_name() === 'cli') { + echo "Hello, CLI user."; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SyntaxStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SyntaxStandard.xml new file mode 100644 index 0000000..1c2457d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SyntaxStandard.xml @@ -0,0 +1,21 @@ + + + + + + + echo "Hello!"; +$array = [1, 2, 3]; + ]]> + + + // Missing semicolon. +$array = [1, 2, 3; // Missing closing bracket. + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml new file mode 100644 index 0000000..1f337f7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml @@ -0,0 +1,23 @@ + + + true, false and null constants must always be uppercase. + ]]> + + + + FALSE || $var === NULL) { + $var = TRUE; +} + ]]> + + + false || $var === null) { + $var = true; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml new file mode 100644 index 0000000..a4c9887 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml new file mode 100644 index 0000000..f4f3e19 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml new file mode 100644 index 0000000..338c838 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml new file mode 100644 index 0000000..2e399b3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml new file mode 100644 index 0000000..7013ffd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml new file mode 100644 index 0000000..a9cd5a6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml @@ -0,0 +1,44 @@ + + + + + + + 'Hello, World!'; +throw new Exception(); +return $newLine; + ]]> + + + 'Hello, World!'; +throw new Exception(); +return +$newLine; + ]]> + + + + + + + + from [1, 2, 3]; + ]]> + + + from [1, 2, 3]; +yield from [1, 2, 3]; +yield +from [1, 2, 3]; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml new file mode 100644 index 0000000..bdd36d4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $var = 1; +} + ]]> + + + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml new file mode 100644 index 0000000..d33b605 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml @@ -0,0 +1,34 @@ + + + + + + + &...$spread) { + bar(...$spread); + + bar( + [...$foo], + ...array_values($keyedArray) + ); +} + ]]> + + + ... $spread) { + bar(... + $spread + ); + + bar( + [... $foo ],.../*comment*/array_values($keyedArray) + ); +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php new file mode 100644 index 0000000..87da8f3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php @@ -0,0 +1,195 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Sniffs\AbstractArraySniff; +use PHP_CodeSniffer\Util\Tokens; + +class ArrayIndentSniff extends AbstractArraySniff +{ + + /** + * The number of spaces each array key should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + + }//end processSingleLineArray() + + + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + $tokens = $phpcsFile->getTokens(); + + // Determine how far indented the entire array declaration should be. + $ignore = Tokens::$emptyTokens; + $ignore[] = T_DOUBLE_ARROW; + $ignore[] = T_COMMA; + $prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true); + $start = $phpcsFile->findStartOfStatement($prev); + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $start, true); + $baseIndent = ($tokens[$first]['column'] - 1); + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + $startIndent = ($tokens[$first]['column'] - 1); + + // If the open brace is not indented to at least to the level of the start + // of the statement, the sniff will conflict with other sniffs trying to + // check indent levels because it's not valid. But we don't enforce exactly + // how far indented it should be. + if ($startIndent < $baseIndent) { + $pluralizeSpace = 's'; + if ($baseIndent === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array open brace not indented correctly; expected at least %s space%s but found %s'; + $data = [ + $baseIndent, + $pluralizeSpace, + $startIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'OpenBraceIncorrect', $data); + if ($fix === true) { + $padding = str_repeat(' ', $baseIndent); + if ($startIndent === 0) { + $phpcsFile->fixer->addContentBefore($first, $padding); + } else { + $phpcsFile->fixer->replaceToken(($first - 1), $padding); + } + } + + return; + }//end if + + $expectedIndent = ($startIndent + $this->indent); + + foreach ($indices as $index) { + if (isset($index['index_start']) === true) { + $start = $index['index_start']; + } else { + $start = $index['value_start']; + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($start - 1), null, true); + if ($tokens[$prev]['line'] === $tokens[$start]['line']) { + // This index isn't the only content on the line + // so we can't check indent rules. + continue; + } + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $start, true); + + $foundIndent = ($tokens[$first]['column'] - 1); + if ($foundIndent === $expectedIndent) { + continue; + } + + $pluralizeSpace = 's'; + if ($expectedIndent === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array key not indented correctly; expected %s space%s but found %s'; + $data = [ + $expectedIndent, + $pluralizeSpace, + $foundIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $first, 'KeyIncorrect', $data); + if ($fix === false) { + continue; + } + + $padding = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($first, $padding); + } else { + $phpcsFile->fixer->replaceToken(($first - 1), $padding); + } + }//end foreach + + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($arrayEnd - 1), null, true); + if ($tokens[$prev]['line'] === $tokens[$arrayEnd]['line']) { + $error = 'Closing brace of array declaration must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNotNewLine'); + if ($fix === true) { + $padding = $phpcsFile->eolChar.str_repeat(' ', $expectedIndent); + $phpcsFile->fixer->addContentBefore($arrayEnd, $padding); + } + + return; + } + + // The close brace must be indented one stop less. + $expectedIndent -= $this->indent; + $foundIndent = ($tokens[$arrayEnd]['column'] - 1); + if ($foundIndent === $expectedIndent) { + return; + } + + $pluralizeSpace = 's'; + if ($expectedIndent === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array close brace not indented correctly; expected %s space%s but found %s'; + $data = [ + $expectedIndent, + $pluralizeSpace, + $foundIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceIncorrect', $data); + if ($fix === false) { + return; + } + + $padding = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($arrayEnd, $padding); + } else { + $phpcsFile->fixer->replaceToken(($arrayEnd - 1), $padding); + } + + }//end processMultiLineArray() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php new file mode 100644 index 0000000..58d2632 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php @@ -0,0 +1,78 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowLongArraySyntaxSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_ARRAY]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no'); + + $error = 'Short array syntax must be used to define arrays'; + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + ) { + // Live coding/parse error, just show the error, don't try and fix it. + $phpcsFile->addError($error, $stackPtr, 'Found'); + return; + } + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + + if ($fix === true) { + $opener = $tokens[$stackPtr]['parenthesis_opener']; + $closer = $tokens[$stackPtr]['parenthesis_closer']; + + $phpcsFile->fixer->beginChangeset(); + + if ($opener === null) { + $phpcsFile->fixer->replaceToken($stackPtr, '[]'); + } else { + $phpcsFile->fixer->replaceToken($stackPtr, ''); + $phpcsFile->fixer->replaceToken($opener, '['); + $phpcsFile->fixer->replaceToken($closer, ']'); + } + + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php new file mode 100644 index 0000000..f982771 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowShortArraySyntaxSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_SHORT_ARRAY]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); + + $error = 'Short array syntax is not allowed'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + + if ($fix === true) { + $tokens = $phpcsFile->getTokens(); + $opener = $tokens[$stackPtr]['bracket_opener']; + $closer = $tokens[$stackPtr]['bracket_closer']; + + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($opener, 'array('); + $phpcsFile->fixer->replaceToken($closer, ')'); + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php new file mode 100644 index 0000000..19ff1ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php @@ -0,0 +1,118 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DuplicateClassNameSniff implements Sniff +{ + + /** + * List of classes that have been found during checking. + * + * @var array + */ + protected $foundClasses = []; + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $namespace = ''; + $findTokens = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_NAMESPACE, + T_CLOSE_TAG, + ]; + + $stackPtr = $phpcsFile->findNext($findTokens, ($stackPtr + 1)); + while ($stackPtr !== false) { + if ($tokens[$stackPtr]['code'] === T_CLOSE_TAG) { + // We can stop here. The sniff will continue from the next open + // tag when PHPCS reaches that token, if there is one. + return; + } + + // Keep track of what namespace we are in. + if ($tokens[$stackPtr]['code'] === T_NAMESPACE) { + $nsEnd = $phpcsFile->findNext( + [ + T_NS_SEPARATOR, + T_STRING, + T_WHITESPACE, + ], + ($stackPtr + 1), + null, + true + ); + + $namespace = trim($phpcsFile->getTokensAsString(($stackPtr + 1), ($nsEnd - $stackPtr - 1))); + $stackPtr = $nsEnd; + } else { + $nameToken = $phpcsFile->findNext(T_STRING, $stackPtr); + $name = $tokens[$nameToken]['content']; + if ($namespace !== '') { + $name = $namespace.'\\'.$name; + } + + $compareName = strtolower($name); + if (isset($this->foundClasses[$compareName]) === true) { + $type = strtolower($tokens[$stackPtr]['content']); + $file = $this->foundClasses[$compareName]['file']; + $line = $this->foundClasses[$compareName]['line']; + $error = 'Duplicate %s name "%s" found; first defined in %s on line %s'; + $data = [ + $type, + $name, + $file, + $line, + ]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } else { + $this->foundClasses[$compareName] = [ + 'file' => $phpcsFile->getFilename(), + 'line' => $tokens[$stackPtr]['line'], + ]; + } + }//end if + + $stackPtr = $phpcsFile->findNext($findTokens, ($stackPtr + 1)); + }//end while + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php new file mode 100644 index 0000000..40291ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php @@ -0,0 +1,124 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OpeningBraceSameLineSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $scopeIdentifier = $phpcsFile->findNext(T_STRING, ($stackPtr + 1)); + $errorData = [strtolower($tokens[$stackPtr]['content']).' '.$tokens[$scopeIdentifier]['content']]; + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $errorData); + return; + } + + $openingBrace = $tokens[$stackPtr]['scope_opener']; + + // Is the brace on the same line as the class/interface/trait declaration ? + $lastClassLineToken = $phpcsFile->findPrevious(T_WHITESPACE, ($openingBrace - 1), $stackPtr, true); + $lastClassLine = $tokens[$lastClassLineToken]['line']; + $braceLine = $tokens[$openingBrace]['line']; + $lineDifference = ($braceLine - $lastClassLine); + + if ($lineDifference > 0) { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'new line'); + $error = 'Opening brace should be on the same line as the declaration for %s'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnNewLine', $errorData); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($lastClassLineToken, ' {'); + $phpcsFile->fixer->replaceToken($openingBrace, ''); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'same line'); + } + + // Is the opening brace the last thing on the line ? + $next = $phpcsFile->findNext(T_WHITESPACE, ($openingBrace + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + if ($next === $tokens[$stackPtr]['scope_closer']) { + // Ignore empty classes. + return; + } + + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + + // Only continue checking if the opening brace looks good. + if ($lineDifference > 0) { + return; + } + + // Is there precisely one space before the opening brace ? + if ($tokens[($openingBrace - 1)]['code'] !== T_WHITESPACE) { + $length = 0; + } else if ($tokens[($openingBrace - 1)]['content'] === "\t") { + $length = '\t'; + } else { + $length = $tokens[($openingBrace - 1)]['length']; + } + + if ($length !== 1) { + $error = 'Expected 1 space before opening brace; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'SpaceBeforeBrace', $data); + if ($fix === true) { + if ($length === 0 || $length === '\t') { + $phpcsFile->fixer->addContentBefore($openingBrace, ' '); + } else { + $phpcsFile->fixer->replaceToken(($openingBrace - 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php new file mode 100644 index 0000000..fecd16a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php @@ -0,0 +1,171 @@ + + * @copyright 2017 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class AssignmentInConditionSniff implements Sniff +{ + + /** + * Assignment tokens to trigger on. + * + * Set in the register() method. + * + * @var array + */ + protected $assignmentTokens = []; + + /** + * The tokens that indicate the start of a condition. + * + * @var array + */ + protected $conditionStartTokens = []; + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + $this->assignmentTokens = Tokens::$assignmentTokens; + unset($this->assignmentTokens[T_DOUBLE_ARROW]); + + $starters = Tokens::$booleanOperators; + $starters[T_SEMICOLON] = T_SEMICOLON; + $starters[T_OPEN_PARENTHESIS] = T_OPEN_PARENTHESIS; + + $this->conditionStartTokens = $starters; + + return [ + T_IF, + T_ELSEIF, + T_FOR, + T_SWITCH, + T_CASE, + T_WHILE, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Find the condition opener/closer. + if ($token['code'] === T_FOR) { + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) { + return; + } + + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($token['parenthesis_opener'] + 1), ($token['parenthesis_closer'])); + if ($semicolon === false) { + return; + } + + $opener = $semicolon; + + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($opener + 1), ($token['parenthesis_closer'])); + if ($semicolon === false) { + return; + } + + $closer = $semicolon; + unset($semicolon); + } else if ($token['code'] === T_CASE) { + if (isset($token['scope_opener']) === false) { + return; + } + + $opener = $stackPtr; + $closer = $token['scope_opener']; + } else { + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) { + return; + } + + $opener = $token['parenthesis_opener']; + $closer = $token['parenthesis_closer']; + }//end if + + $startPos = $opener; + + do { + $hasAssignment = $phpcsFile->findNext($this->assignmentTokens, ($startPos + 1), $closer); + if ($hasAssignment === false) { + return; + } + + // Examine whether the left side is a variable. + $hasVariable = false; + $conditionStart = $startPos; + $altConditionStart = $phpcsFile->findPrevious($this->conditionStartTokens, ($hasAssignment - 1), $startPos); + if ($altConditionStart !== false) { + $conditionStart = $altConditionStart; + } + + for ($i = $hasAssignment; $i > $conditionStart; $i--) { + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) { + continue; + } + + // If this is a variable or array, we've seen all we need to see. + if ($tokens[$i]['code'] === T_VARIABLE || $tokens[$i]['code'] === T_CLOSE_SQUARE_BRACKET) { + $hasVariable = true; + break; + } + + // If this is a function call or something, we are OK. + if ($tokens[$i]['code'] === T_CLOSE_PARENTHESIS) { + break; + } + } + + if ($hasVariable === true) { + $errorCode = 'Found'; + if ($token['code'] === T_WHILE) { + $errorCode = 'FoundInWhileCondition'; + } + + $phpcsFile->addWarning( + 'Variable assignment found within a condition. Did you mean to do a comparison ?', + $hasAssignment, + $errorCode + ); + } + + $startPos = $hasAssignment; + } while ($startPos < $closer); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php new file mode 100644 index 0000000..3ebfccc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php @@ -0,0 +1,162 @@ + + * @copyright 2017 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EmptyPHPStatementSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_SEMICOLON, + T_CLOSE_TAG, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + switch ($tokens[$stackPtr]['type']) { + // Detect `something();;`. + case 'T_SEMICOLON': + $prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + + if ($prevNonEmpty === false) { + return; + } + + if ($tokens[$prevNonEmpty]['code'] !== T_SEMICOLON + && $tokens[$prevNonEmpty]['code'] !== T_OPEN_TAG + && $tokens[$prevNonEmpty]['code'] !== T_OPEN_TAG_WITH_ECHO + ) { + if (isset($tokens[$prevNonEmpty]['scope_condition']) === false) { + return; + } + + if ($tokens[$prevNonEmpty]['scope_opener'] !== $prevNonEmpty + && $tokens[$prevNonEmpty]['code'] !== T_CLOSE_CURLY_BRACKET + ) { + return; + } + + $scopeOwner = $tokens[$tokens[$prevNonEmpty]['scope_condition']]['code']; + if ($scopeOwner === T_CLOSURE || $scopeOwner === T_ANON_CLASS || $scopeOwner === T_MATCH) { + return; + } + + // Else, it's something like `if (foo) {};` and the semi-colon is not needed. + } + + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $nested = $tokens[$stackPtr]['nested_parenthesis']; + $lastCloser = array_pop($nested); + if (isset($tokens[$lastCloser]['parenthesis_owner']) === true + && $tokens[$tokens[$lastCloser]['parenthesis_owner']]['code'] === T_FOR + ) { + // Empty for() condition. + return; + } + } + + $fix = $phpcsFile->addFixableWarning( + 'Empty PHP statement detected: superfluous semi-colon.', + $stackPtr, + 'SemicolonWithoutCodeDetected' + ); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + if ($tokens[$prevNonEmpty]['code'] === T_OPEN_TAG + || $tokens[$prevNonEmpty]['code'] === T_OPEN_TAG_WITH_ECHO + ) { + // Check for superfluous whitespace after the semi-colon which will be + // removed as the `fixer->replaceToken(($stackPtr + 1), $replacement); + } + } + + for ($i = $stackPtr; $i > $prevNonEmpty; $i--) { + if ($tokens[$i]['code'] !== T_SEMICOLON + && $tokens[$i]['code'] !== T_WHITESPACE + ) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + break; + + // Detect ``. + case 'T_CLOSE_TAG': + $prevNonEmpty = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + + if ($prevNonEmpty === false + || ($tokens[$prevNonEmpty]['code'] !== T_OPEN_TAG + && $tokens[$prevNonEmpty]['code'] !== T_OPEN_TAG_WITH_ECHO) + ) { + return; + } + + $fix = $phpcsFile->addFixableWarning( + 'Empty PHP open/close tag combination detected.', + $prevNonEmpty, + 'EmptyPHPOpenCloseTagsDetected' + ); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = $prevNonEmpty; $i <= $stackPtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + break; + + default: + // Deliberately left empty. + break; + }//end switch + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php new file mode 100644 index 0000000..ded042a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php @@ -0,0 +1,97 @@ + + * stmt { + * // foo + * } + * stmt (conditions) { + * // foo + * } + * + * + * @author Manuel Pichler + * @author Greg Sherwood + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EmptyStatementSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_TRY, + T_CATCH, + T_FINALLY, + T_DO, + T_ELSE, + T_ELSEIF, + T_FOR, + T_FOREACH, + T_IF, + T_SWITCH, + T_WHILE, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip statements without a body. + if (isset($token['scope_opener']) === false) { + return; + } + + $next = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($token['scope_opener'] + 1), + ($token['scope_closer'] - 1), + true + ); + + if ($next !== false) { + return; + } + + // Get token identifier. + $name = strtoupper($token['content']); + $error = 'Empty %s statement detected'; + $phpcsFile->addError($error, $stackPtr, 'Detected'.ucfirst(strtolower($name)), [$name]); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php new file mode 100644 index 0000000..726b32c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php @@ -0,0 +1,91 @@ + + * class Foo + * { + * public function bar($x) + * { + * for (;true;) true; // No Init or Update part, may as well be: while (true) + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ForLoopShouldBeWhileLoopSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FOR]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip invalid statement. + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) { + return; + } + + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + + $parts = [ + 0, + 0, + 0, + ]; + $index = 0; + + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === T_SEMICOLON) { + ++$index; + } else if (isset(Tokens::$emptyTokens[$code]) === false) { + ++$parts[$index]; + } + } + + if ($parts[0] === 0 && $parts[2] === 0 && $parts[1] > 0) { + $error = 'This FOR loop can be simplified to a WHILE loop'; + $phpcsFile->addWarning($error, $stackPtr, 'CanSimplify'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php new file mode 100644 index 0000000..45b4f73 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php @@ -0,0 +1,101 @@ + + * class Foo + * { + * public function bar($x) + * { + * $a = array(1, 2, 3, 4); + * for ($i = 0; $i < count($a); $i++) { + * $a[$i] *= $i; + * } + * } + * } + * + * + * @author Greg Sherwood + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ForLoopWithTestFunctionCallSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FOR]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip invalid statement. + if (isset($token['parenthesis_opener']) === false) { + return; + } + + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + + $position = 0; + + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === T_SEMICOLON) { + ++$position; + } + + if ($position < 1) { + continue; + } else if ($position > 1) { + break; + } else if ($code !== T_VARIABLE && $code !== T_STRING) { + continue; + } + + // Find next non empty token, if it is a open curly brace we have a + // function call. + $index = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + + if ($tokens[$index]['code'] === T_OPEN_PARENTHESIS) { + $error = 'Avoid function calls in a FOR loop test part'; + $phpcsFile->addWarning($error, $stackPtr, 'NotAllowed'); + break; + } + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php new file mode 100644 index 0000000..63e925f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php @@ -0,0 +1,134 @@ + + * class Foo + * { + * public function bar($x) + * { + * for ($i = 0; $i < 10; $i++) + * { + * for ($k = 0; $k < 20; $i++) + * { + * echo 'Hello'; + * } + * } + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class JumbledIncrementerSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FOR]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip for-loop without body. + if (isset($token['scope_opener']) === false) { + return; + } + + // Find incrementors for outer loop. + $outer = $this->findIncrementers($tokens, $token); + + // Skip if empty. + if (count($outer) === 0) { + return; + } + + // Find nested for loops. + $start = ++$token['scope_opener']; + $end = --$token['scope_closer']; + + for (; $start <= $end; ++$start) { + if ($tokens[$start]['code'] !== T_FOR) { + continue; + } + + $inner = $this->findIncrementers($tokens, $tokens[$start]); + $diff = array_intersect($outer, $inner); + + if (count($diff) !== 0) { + $error = 'Loop incrementor (%s) jumbling with inner loop'; + $data = [join(', ', $diff)]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } + } + + }//end process() + + + /** + * Get all used variables in the incrementer part of a for statement. + * + * @param array $tokens Array with all code sniffer tokens. + * @param array $token Current for loop token + * + * @return string[] List of all found incrementer variables. + */ + protected function findIncrementers(array $tokens, array $token) + { + // Skip invalid statement. + if (isset($token['parenthesis_opener']) === false) { + return []; + } + + $start = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + + $incrementers = []; + $semicolons = 0; + for ($next = $start; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === T_SEMICOLON) { + ++$semicolons; + } else if ($semicolons === 2 && $code === T_VARIABLE) { + $incrementers[] = $tokens[$next]['content']; + } + } + + return $incrementers; + + }//end findIncrementers() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php new file mode 100644 index 0000000..db71a96 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php @@ -0,0 +1,93 @@ +true or false + * + * + * class Foo + * { + * public function close() + * { + * if (true) + * { + * // ... + * } + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UnconditionalIfStatementSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_ELSEIF, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip if statement without body. + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) { + return; + } + + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + + $goodCondition = false; + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + + if (isset(Tokens::$emptyTokens[$code]) === true) { + continue; + } else if ($code !== T_TRUE && $code !== T_FALSE) { + $goodCondition = true; + } + } + + if ($goodCondition === false) { + $error = 'Avoid IF statements that are always true or false'; + $phpcsFile->addWarning($error, $stackPtr, 'Found'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php new file mode 100644 index 0000000..2f4faa8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php @@ -0,0 +1,88 @@ + + * final class Foo + * { + * public final function bar() + * { + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class UnnecessaryFinalModifierSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLASS]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip for statements without body. + if (isset($token['scope_opener']) === false) { + return; + } + + if ($phpcsFile->getClassProperties($stackPtr)['is_final'] === false) { + // This class is not final so we don't need to check it. + return; + } + + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + + for (; $next <= $end; ++$next) { + if ($tokens[$next]['code'] === T_FINAL) { + $error = 'Unnecessary FINAL modifier in FINAL class'; + $phpcsFile->addWarning($error, $next, 'Found'); + } + + // Skip over the contents of functions as those can't contain the `final` keyword anyway. + if ($tokens[$next]['code'] === T_FUNCTION + && isset($tokens[$next]['scope_closer']) === true + ) { + $next = $tokens[$next]['scope_closer']; + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php new file mode 100644 index 0000000..66fe781 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php @@ -0,0 +1,304 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UnusedFunctionParameterSniff implements Sniff +{ + + /** + * The list of class type hints which will be ignored. + * + * @var array + */ + public $ignoreTypeHints = []; + + /** + * A list of all PHP magic methods with fixed method signatures. + * + * Note: `__construct()` and `__invoke()` are excluded on purpose + * as their method signature is not fixed. + * + * @var array + */ + private $magicMethods = [ + '__destruct' => true, + '__call' => true, + '__callstatic' => true, + '__get' => true, + '__set' => true, + '__isset' => true, + '__unset' => true, + '__sleep' => true, + '__wakeup' => true, + '__serialize' => true, + '__unserialize' => true, + '__tostring' => true, + '__set_state' => true, + '__clone' => true, + '__debuginfo' => true, + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + T_FN, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip broken function declarations. + if (isset($token['scope_opener']) === false || isset($token['parenthesis_opener']) === false) { + return; + } + + $errorCode = 'Found'; + $implements = false; + $extends = false; + + if ($token['code'] === T_FUNCTION) { + $classPtr = $phpcsFile->getCondition($stackPtr, T_CLASS); + if ($classPtr !== false) { + // Check for magic methods and ignore these as the method signature cannot be changed. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if (empty($methodName) === false) { + $methodNameLc = strtolower($methodName); + if (isset($this->magicMethods[$methodNameLc]) === true) { + return; + } + } + + // Check for extends/implements and adjust the error code when found. + $implements = $phpcsFile->findImplementedInterfaceNames($classPtr); + $extends = $phpcsFile->findExtendedClassName($classPtr); + if ($extends !== false) { + $errorCode .= 'InExtendedClass'; + } else if ($implements !== false) { + $errorCode .= 'InImplementedInterface'; + } + } + }//end if + + $params = []; + $methodParams = $phpcsFile->getMethodParameters($stackPtr); + + // Skip when no parameters found. + $methodParamsCount = count($methodParams); + if ($methodParamsCount === 0) { + return; + } + + foreach ($methodParams as $param) { + if (isset($param['property_visibility']) === true) { + // Ignore constructor property promotion. + continue; + } + + $params[$param['name']] = $stackPtr; + } + + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + + // Check the end token for arrow functions as + // they can end at a content token due to not having + // a clearly defined closing token. + if ($token['code'] === T_FN) { + ++$end; + } + + $foundContent = false; + $validTokens = [ + T_HEREDOC => T_HEREDOC, + T_NOWDOC => T_NOWDOC, + T_END_HEREDOC => T_END_HEREDOC, + T_END_NOWDOC => T_END_NOWDOC, + T_DOUBLE_QUOTED_STRING => T_DOUBLE_QUOTED_STRING, + ]; + $validTokens += Tokens::$emptyTokens; + + for (; $next <= $end; ++$next) { + $token = $tokens[$next]; + $code = $token['code']; + + // Ignorable tokens. + if (isset(Tokens::$emptyTokens[$code]) === true) { + continue; + } + + if ($foundContent === false) { + // A throw statement as the first content indicates an interface method. + if ($code === T_THROW && $implements !== false) { + return; + } + + // A return statement as the first content indicates an interface method. + if ($code === T_RETURN) { + $tmp = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + if ($tmp === false && $implements !== false) { + return; + } + + // There is a return. + if ($tokens[$tmp]['code'] === T_SEMICOLON && $implements !== false) { + return; + } + + $tmp = $phpcsFile->findNext(Tokens::$emptyTokens, ($tmp + 1), null, true); + if ($tmp !== false && $tokens[$tmp]['code'] === T_SEMICOLON && $implements !== false) { + // There is a return . + return; + } + }//end if + }//end if + + $foundContent = true; + + if ($code === T_VARIABLE && isset($params[$token['content']]) === true) { + unset($params[$token['content']]); + } else if ($code === T_DOLLAR) { + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true); + if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) { + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] === T_STRING) { + $varContent = '$'.$tokens[$nextToken]['content']; + if (isset($params[$varContent]) === true) { + unset($params[$varContent]); + } + } + } + } else if ($code === T_DOUBLE_QUOTED_STRING + || $code === T_START_HEREDOC + || $code === T_START_NOWDOC + ) { + // Tokenize strings that can contain variables. + // Make sure the string is re-joined if it occurs over multiple lines. + $content = $token['content']; + for ($i = ($next + 1); $i <= $end; $i++) { + if (isset($validTokens[$tokens[$i]['code']]) === true) { + $content .= $tokens[$i]['content']; + $next++; + } else { + break; + } + } + + $stringTokens = token_get_all(sprintf('', $content)); + foreach ($stringTokens as $stringPtr => $stringToken) { + if (is_array($stringToken) === false) { + continue; + } + + $varContent = ''; + if ($stringToken[0] === T_DOLLAR_OPEN_CURLY_BRACES) { + $varContent = '$'.$stringTokens[($stringPtr + 1)][1]; + } else if ($stringToken[0] === T_VARIABLE) { + $varContent = $stringToken[1]; + } + + if ($varContent !== '' && isset($params[$varContent]) === true) { + unset($params[$varContent]); + } + } + }//end if + }//end for + + if ($foundContent === true && count($params) > 0) { + $error = 'The method parameter %s is never used'; + + // If there is only one parameter and it is unused, no need for additional errorcode toggling logic. + if ($methodParamsCount === 1) { + foreach ($params as $paramName => $position) { + if (in_array($methodParams[0]['type_hint'], $this->ignoreTypeHints, true) === true) { + continue; + } + + $data = [$paramName]; + $phpcsFile->addWarning($error, $position, $errorCode, $data); + } + + return; + } + + $foundLastUsed = false; + $lastIndex = ($methodParamsCount - 1); + $errorInfo = []; + for ($i = $lastIndex; $i >= 0; --$i) { + if ($foundLastUsed !== false) { + if (isset($params[$methodParams[$i]['name']]) === true) { + $errorInfo[$methodParams[$i]['name']] = [ + 'position' => $params[$methodParams[$i]['name']], + 'errorcode' => $errorCode.'BeforeLastUsed', + 'typehint' => $methodParams[$i]['type_hint'], + ]; + } + } else { + if (isset($params[$methodParams[$i]['name']]) === false) { + $foundLastUsed = true; + } else { + $errorInfo[$methodParams[$i]['name']] = [ + 'position' => $params[$methodParams[$i]['name']], + 'errorcode' => $errorCode.'AfterLastUsed', + 'typehint' => $methodParams[$i]['type_hint'], + ]; + } + } + }//end for + + if (count($errorInfo) > 0) { + $errorInfo = array_reverse($errorInfo); + foreach ($errorInfo as $paramName => $info) { + if (in_array($info['typehint'], $this->ignoreTypeHints, true) === true) { + continue; + } + + $data = [$paramName]; + $phpcsFile->addWarning($error, $info['position'], $info['errorcode'], $data); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php new file mode 100644 index 0000000..1b79fd3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php @@ -0,0 +1,161 @@ + + * class FooBar { + * public function __construct($a, $b) { + * parent::__construct($a, $b); + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UselessOverridingMethodSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + + // Skip function without body. + if (isset($token['scope_opener']) === false) { + return; + } + + // Get function name. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + + // Get all parameters from method signature. + $signature = []; + foreach ($phpcsFile->getMethodParameters($stackPtr) as $param) { + $signature[] = $param['name']; + } + + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + + if (isset(Tokens::$emptyTokens[$code]) === true) { + continue; + } else if ($code === T_RETURN) { + continue; + } + + break; + } + + // Any token except 'parent' indicates correct code. + if ($tokens[$next]['code'] !== T_PARENT) { + return; + } + + // Find next non empty token index, should be double colon. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + + // Skip for invalid code. + if ($next === false || $tokens[$next]['code'] !== T_DOUBLE_COLON) { + return; + } + + // Find next non empty token index, should be the function name. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + + // Skip for invalid code or other method. + if ($next === false || $tokens[$next]['content'] !== $methodName) { + return; + } + + // Find next non empty token index, should be the open parenthesis. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + + // Skip for invalid code. + if ($next === false || $tokens[$next]['code'] !== T_OPEN_PARENTHESIS) { + return; + } + + $parameters = ['']; + $parenthesisCount = 1; + $count = count($tokens); + for (++$next; $next < $count; ++$next) { + $code = $tokens[$next]['code']; + + if ($code === T_OPEN_PARENTHESIS) { + ++$parenthesisCount; + } else if ($code === T_CLOSE_PARENTHESIS) { + --$parenthesisCount; + } else if ($parenthesisCount === 1 && $code === T_COMMA) { + $parameters[] = ''; + } else if (isset(Tokens::$emptyTokens[$code]) === false) { + $parameters[(count($parameters) - 1)] .= $tokens[$next]['content']; + } + + if ($parenthesisCount === 0) { + break; + } + }//end for + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + if ($next === false || $tokens[$next]['code'] !== T_SEMICOLON) { + return; + } + + // Check rest of the scope. + for (++$next; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + // Skip for any other content. + if (isset(Tokens::$emptyTokens[$code]) === false) { + return; + } + } + + $parameters = array_map('trim', $parameters); + $parameters = array_filter($parameters); + + if (count($parameters) === count($signature) && $parameters === $signature) { + $phpcsFile->addWarning('Possible useless method overriding detected', $stackPtr, 'Found'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php new file mode 100644 index 0000000..f34ffc2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php @@ -0,0 +1,357 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DocCommentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DOC_COMMENT_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['comment_closer']) === false + || ($tokens[$tokens[$stackPtr]['comment_closer']]['content'] === '' + && $tokens[$stackPtr]['comment_closer'] === ($phpcsFile->numTokens - 1)) + ) { + // Don't process an unfinished comment during live coding. + return; + } + + $commentStart = $stackPtr; + $commentEnd = $tokens[$stackPtr]['comment_closer']; + + $empty = [ + T_DOC_COMMENT_WHITESPACE, + T_DOC_COMMENT_STAR, + ]; + + $short = $phpcsFile->findNext($empty, ($stackPtr + 1), $commentEnd, true); + if ($short === false) { + // No content at all. + $error = 'Doc comment is empty'; + $phpcsFile->addError($error, $stackPtr, 'Empty'); + return; + } + + // The first line of the comment should just be the /** code. + if ($tokens[$short]['line'] === $tokens[$stackPtr]['line']) { + $error = 'The open comment tag must be the only content on the line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentAfterOpen'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($stackPtr); + $phpcsFile->fixer->addContentBefore($short, '* '); + $phpcsFile->fixer->endChangeset(); + } + } + + // The last line of the comment should just be the */ code. + $prev = $phpcsFile->findPrevious($empty, ($commentEnd - 1), $stackPtr, true); + if ($tokens[$prev]['line'] === $tokens[$commentEnd]['line']) { + $error = 'The close comment tag must be the only content on the line'; + $fix = $phpcsFile->addFixableError($error, $commentEnd, 'ContentBeforeClose'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($commentEnd); + } + } + + // Check for additional blank lines at the end of the comment. + if ($tokens[$prev]['line'] < ($tokens[$commentEnd]['line'] - 1)) { + $error = 'Additional blank lines found at end of doc comment'; + $fix = $phpcsFile->addFixableError($error, $commentEnd, 'SpacingAfter'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $commentEnd; $i++) { + if ($tokens[($i + 1)]['line'] === $tokens[$commentEnd]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + // Check for a comment description. + if ($tokens[$short]['code'] !== T_DOC_COMMENT_STRING) { + $error = 'Missing short description in doc comment'; + $phpcsFile->addError($error, $stackPtr, 'MissingShort'); + } else { + // No extra newline before short description. + if ($tokens[$short]['line'] !== ($tokens[$stackPtr]['line'] + 1)) { + $error = 'Doc comment short description must be on the first line'; + $fix = $phpcsFile->addFixableError($error, $short, 'SpacingBeforeShort'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $stackPtr; $i < $short; $i++) { + if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { + continue; + } else if ($tokens[$i]['line'] === $tokens[$short]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + // Account for the fact that a short description might cover + // multiple lines. + $shortContent = $tokens[$short]['content']; + $shortEnd = $short; + for ($i = ($short + 1); $i < $commentEnd; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) { + if ($tokens[$i]['line'] === ($tokens[$shortEnd]['line'] + 1)) { + $shortContent .= $tokens[$i]['content']; + $shortEnd = $i; + } else { + break; + } + } + } + + if (preg_match('/^\p{Ll}/u', $shortContent) === 1) { + $error = 'Doc comment short description must start with a capital letter'; + $phpcsFile->addError($error, $short, 'ShortNotCapital'); + } + + $long = $phpcsFile->findNext($empty, ($shortEnd + 1), ($commentEnd - 1), true); + if ($long !== false && $tokens[$long]['code'] === T_DOC_COMMENT_STRING) { + if ($tokens[$long]['line'] !== ($tokens[$shortEnd]['line'] + 2)) { + $error = 'There must be exactly one blank line between descriptions in a doc comment'; + $fix = $phpcsFile->addFixableError($error, $long, 'SpacingBetween'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($shortEnd + 1); $i < $long; $i++) { + if ($tokens[$i]['line'] === $tokens[$shortEnd]['line']) { + continue; + } else if ($tokens[$i]['line'] === ($tokens[$long]['line'] - 1)) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + if (preg_match('/^\p{Ll}/u', $tokens[$long]['content']) === 1) { + $error = 'Doc comment long description must start with a capital letter'; + $phpcsFile->addError($error, $long, 'LongNotCapital'); + } + }//end if + }//end if + + if (empty($tokens[$commentStart]['comment_tags']) === true) { + // No tags in the comment. + return; + } + + $firstTag = $tokens[$commentStart]['comment_tags'][0]; + $prev = $phpcsFile->findPrevious($empty, ($firstTag - 1), $stackPtr, true); + if ($tokens[$firstTag]['line'] !== ($tokens[$prev]['line'] + 2) + && $tokens[$prev]['code'] !== T_DOC_COMMENT_OPEN_TAG + ) { + $error = 'There must be exactly one blank line before the tags in a doc comment'; + $fix = $phpcsFile->addFixableError($error, $firstTag, 'SpacingBeforeTags'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $firstTag; $i++) { + if ($tokens[$i]['line'] === $tokens[$firstTag]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $indent = str_repeat(' ', $tokens[$stackPtr]['column']); + $phpcsFile->fixer->addContent($prev, $phpcsFile->eolChar.$indent.'*'.$phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } + + // Break out the tags into groups and check alignment within each. + // A tag group is one where there are no blank lines between tags. + // The param tag group is special as it requires all @param tags to be inside. + $tagGroups = []; + $groupid = 0; + $paramGroupid = null; + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($pos > 0) { + $prev = $phpcsFile->findPrevious( + T_DOC_COMMENT_STRING, + ($tag - 1), + $tokens[$commentStart]['comment_tags'][($pos - 1)] + ); + + if ($prev === false) { + $prev = $tokens[$commentStart]['comment_tags'][($pos - 1)]; + } + + if ($tokens[$prev]['line'] !== ($tokens[$tag]['line'] - 1)) { + $groupid++; + } + } + + if ($tokens[$tag]['content'] === '@param') { + if ($paramGroupid !== null + && $paramGroupid !== $groupid + ) { + $error = 'Parameter tags must be grouped together in a doc comment'; + $phpcsFile->addError($error, $tag, 'ParamGroup'); + } + + if ($paramGroupid === null) { + $paramGroupid = $groupid; + } + }//end if + + $tagGroups[$groupid][] = $tag; + }//end foreach + + foreach ($tagGroups as $groupid => $group) { + $maxLength = 0; + $paddings = []; + foreach ($group as $pos => $tag) { + if ($paramGroupid === $groupid + && $tokens[$tag]['content'] !== '@param' + ) { + $error = 'Tag %s cannot be grouped with parameter tags in a doc comment'; + $data = [$tokens[$tag]['content']]; + $phpcsFile->addError($error, $tag, 'NonParamGroup', $data); + } + + $tagLength = $tokens[$tag]['length']; + if ($tagLength > $maxLength) { + $maxLength = $tagLength; + } + + // Check for a value. No value means no padding needed. + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string !== false && $tokens[$string]['line'] === $tokens[$tag]['line']) { + $paddings[$tag] = $tokens[($tag + 1)]['length']; + } + } + + // Check that there was single blank line after the tag block + // but account for multi-line tag comments. + $find = Tokens::$phpcsCommentTokens; + $find[T_DOC_COMMENT_TAG] = T_DOC_COMMENT_TAG; + + $lastTag = $group[$pos]; + $next = $phpcsFile->findNext($find, ($lastTag + 3), $commentEnd); + if ($next !== false) { + $prev = $phpcsFile->findPrevious([T_DOC_COMMENT_TAG, T_DOC_COMMENT_STRING], ($next - 1), $commentStart); + if ($tokens[$next]['line'] !== ($tokens[$prev]['line'] + 2)) { + $error = 'There must be a single blank line after a tag group'; + $fix = $phpcsFile->addFixableError($error, $lastTag, 'SpacingAfterTagGroup'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $indent = str_repeat(' ', $tokens[$stackPtr]['column']); + $phpcsFile->fixer->addContent($prev, $phpcsFile->eolChar.$indent.'*'.$phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + // Now check paddings. + foreach ($paddings as $tag => $padding) { + $required = ($maxLength - $tokens[$tag]['length'] + 1); + + if ($padding !== $required) { + $error = 'Tag value for %s tag indented incorrectly; expected %s spaces but found %s'; + $data = [ + $tokens[$tag]['content'], + $required, + $padding, + ]; + + $fix = $phpcsFile->addFixableError($error, ($tag + 1), 'TagValueIndent', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($tag + 1), str_repeat(' ', $required)); + } + } + } + }//end foreach + + // If there is a param group, it needs to be first. + if ($paramGroupid !== null && $paramGroupid !== 0) { + $error = 'Parameter tags must be defined first in a doc comment'; + $phpcsFile->addError($error, $tagGroups[$paramGroupid][0], 'ParamNotFirst'); + } + + $foundTags = []; + foreach ($tokens[$stackPtr]['comment_tags'] as $pos => $tag) { + $tagName = $tokens[$tag]['content']; + if (isset($foundTags[$tagName]) === true) { + $lastTag = $tokens[$stackPtr]['comment_tags'][($pos - 1)]; + if ($tokens[$lastTag]['content'] !== $tagName) { + $error = 'Tags must be grouped together in a doc comment'; + $phpcsFile->addError($error, $tag, 'TagsNotGrouped'); + } + + continue; + } + + $foundTags[$tagName] = true; + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php new file mode 100644 index 0000000..b78a659 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php @@ -0,0 +1,78 @@ + + * @author Sam Graham + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FixmeSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return array_diff(Tokens::$commentTokens, Tokens::$phpcsCommentTokens); + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $matches = []; + preg_match('/(?:\A|[^\p{L}]+)fixme([^\p{L}]+(.*)|\Z)/ui', $content, $matches); + if (empty($matches) === false) { + // Clear whitespace and some common characters not required at + // the end of a fixme message to make the error more informative. + $type = 'CommentFound'; + $fixmeMessage = trim($matches[1]); + $fixmeMessage = trim($fixmeMessage, '-:[](). '); + $error = 'Comment refers to a FIXME task'; + $data = [$fixmeMessage]; + if ($fixmeMessage !== '') { + $type = 'TaskFound'; + $error .= ' "%s"'; + } + + $phpcsFile->addError($error, $stackPtr, $type, $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php new file mode 100644 index 0000000..d24111c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class TodoSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return array_diff(Tokens::$commentTokens, Tokens::$phpcsCommentTokens); + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $matches = []; + preg_match('/(?:\A|[^\p{L}]+)todo([^\p{L}]+(.*)|\Z)/ui', $content, $matches); + if (empty($matches) === false) { + // Clear whitespace and some common characters not required at + // the end of a to-do message to make the warning more informative. + $type = 'CommentFound'; + $todoMessage = trim($matches[1]); + $todoMessage = trim($todoMessage, '-:[](). '); + $error = 'Comment refers to a TODO task'; + $data = [$todoMessage]; + if ($todoMessage !== '') { + $type = 'TaskFound'; + $error .= ' "%s"'; + } + + $phpcsFile->addWarning($error, $stackPtr, $type, $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php new file mode 100644 index 0000000..d82931c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php @@ -0,0 +1,188 @@ + + * @author Mark Scherer + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DisallowYodaConditionsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$comparisonTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $previousIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + $relevantTokens = [ + T_CLOSE_SHORT_ARRAY, + T_CLOSE_PARENTHESIS, + T_TRUE, + T_FALSE, + T_NULL, + T_LNUMBER, + T_DNUMBER, + T_CONSTANT_ENCAPSED_STRING, + ]; + + if ($previousIndex === false + || in_array($tokens[$previousIndex]['code'], $relevantTokens, true) === false + ) { + return; + } + + if ($tokens[$previousIndex]['code'] === T_CLOSE_SHORT_ARRAY) { + $previousIndex = $tokens[$previousIndex]['bracket_opener']; + if ($this->isArrayStatic($phpcsFile, $previousIndex) === false) { + return; + } + } + + $prevIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($previousIndex - 1), null, true); + if ($prevIndex === false) { + return; + } + + if (in_array($tokens[$prevIndex]['code'], Tokens::$arithmeticTokens, true) === true) { + return; + } + + if ($tokens[$prevIndex]['code'] === T_STRING_CONCAT) { + return; + } + + // Is it a parenthesis. + if ($tokens[$previousIndex]['code'] === T_CLOSE_PARENTHESIS) { + // Check what exists inside the parenthesis. + $closeParenthesisIndex = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($tokens[$previousIndex]['parenthesis_opener'] - 1), + null, + true + ); + + if ($closeParenthesisIndex === false || $tokens[$closeParenthesisIndex]['code'] !== T_ARRAY) { + if ($tokens[$closeParenthesisIndex]['code'] === T_STRING) { + return; + } + + // If it is not an array check what is inside. + $found = $phpcsFile->findPrevious( + T_VARIABLE, + ($previousIndex - 1), + $tokens[$previousIndex]['parenthesis_opener'] + ); + + // If a variable exists, it is not Yoda. + if ($found !== false) { + return; + } + + // If there is nothing inside the parenthesis, it it not a Yoda. + $opener = $tokens[$previousIndex]['parenthesis_opener']; + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($previousIndex - 1), ($opener + 1), true); + if ($prev === false) { + return; + } + } else if ($tokens[$closeParenthesisIndex]['code'] === T_ARRAY + && $this->isArrayStatic($phpcsFile, $closeParenthesisIndex) === false + ) { + return; + }//end if + }//end if + + $phpcsFile->addError( + 'Usage of Yoda conditions is not allowed; switch the expression order', + $stackPtr, + 'Found' + ); + + }//end process() + + + /** + * Determines if an array is a static definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $arrayToken The position of the array token. + * + * @return bool + */ + public function isArrayStatic(File $phpcsFile, $arrayToken) + { + $tokens = $phpcsFile->getTokens(); + + $arrayEnd = null; + if ($tokens[$arrayToken]['code'] === T_OPEN_SHORT_ARRAY) { + $start = $arrayToken; + $end = $tokens[$arrayToken]['bracket_closer']; + } else if ($tokens[$arrayToken]['code'] === T_ARRAY) { + $start = $tokens[$arrayToken]['parenthesis_opener']; + $end = $tokens[$arrayToken]['parenthesis_closer']; + } else { + return true; + } + + $staticTokens = Tokens::$emptyTokens; + $staticTokens += Tokens::$textStringTokens; + $staticTokens += Tokens::$assignmentTokens; + $staticTokens += Tokens::$equalityTokens; + $staticTokens += Tokens::$comparisonTokens; + $staticTokens += Tokens::$arithmeticTokens; + $staticTokens += Tokens::$operators; + $staticTokens += Tokens::$booleanOperators; + $staticTokens += Tokens::$castTokens; + $staticTokens += Tokens::$bracketTokens; + $staticTokens += [ + T_DOUBLE_ARROW => T_DOUBLE_ARROW, + T_COMMA => T_COMMA, + T_TRUE => T_TRUE, + T_FALSE => T_FALSE, + ]; + + for ($i = ($start + 1); $i < $end; $i++) { + if (isset($tokens[$i]['scope_closer']) === true) { + $i = $tokens[$i]['scope_closer']; + continue; + } + + if (isset($staticTokens[$tokens[$i]['code']]) === false) { + return false; + } + } + + return true; + + }//end isArrayStatic() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php new file mode 100644 index 0000000..8a4884d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php @@ -0,0 +1,381 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class InlineControlStructureSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = true; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_ELSE, + T_ELSEIF, + T_FOREACH, + T_WHILE, + T_DO, + T_SWITCH, + T_FOR, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void|int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_opener']) === true) { + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no'); + return; + } + + // Ignore the ELSE in ELSE IF. We'll process the IF part later. + if ($tokens[$stackPtr]['code'] === T_ELSE) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_IF) { + return; + } + } + + if ($tokens[$stackPtr]['code'] === T_WHILE || $tokens[$stackPtr]['code'] === T_FOR) { + // This could be from a DO WHILE, which doesn't have an opening brace or a while/for without body. + if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) { + $afterParensCloser = $phpcsFile->findNext(Tokens::$emptyTokens, ($tokens[$stackPtr]['parenthesis_closer'] + 1), null, true); + if ($afterParensCloser === false) { + // Live coding. + return; + } + + if ($tokens[$afterParensCloser]['code'] === T_SEMICOLON) { + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no'); + return; + } + } + + // In Javascript DO WHILE loops without curly braces are legal. This + // is only valid if a single statement is present between the DO and + // the WHILE. We can detect this by checking only a single semicolon + // is present between them. + if ($tokens[$stackPtr]['code'] === T_WHILE && $phpcsFile->tokenizerType === 'JS') { + $lastDo = $phpcsFile->findPrevious(T_DO, ($stackPtr - 1)); + $lastSemicolon = $phpcsFile->findPrevious(T_SEMICOLON, ($stackPtr - 1)); + if ($lastDo !== false && $lastSemicolon !== false && $lastDo < $lastSemicolon) { + $precedingSemicolon = $phpcsFile->findPrevious(T_SEMICOLON, ($lastSemicolon - 1)); + if ($precedingSemicolon === false || $precedingSemicolon < $lastDo) { + return; + } + } + } + }//end if + + if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === false + && $tokens[$stackPtr]['code'] !== T_ELSE + ) { + if ($tokens[$stackPtr]['code'] !== T_DO) { + // Live coding or parse error. + return; + } + + $nextWhile = $phpcsFile->findNext(T_WHILE, ($stackPtr + 1)); + if ($nextWhile !== false + && isset($tokens[$nextWhile]['parenthesis_opener'], $tokens[$nextWhile]['parenthesis_closer']) === false + ) { + // Live coding or parse error. + return; + } + + unset($nextWhile); + } + + $start = $stackPtr; + if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) { + $start = $tokens[$stackPtr]['parenthesis_closer']; + } + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($start + 1), null, true); + if ($nextNonEmpty === false) { + // Live coding or parse error. + return; + } + + if ($tokens[$nextNonEmpty]['code'] === T_OPEN_CURLY_BRACKET + || $tokens[$nextNonEmpty]['code'] === T_COLON + ) { + // T_CLOSE_CURLY_BRACKET missing, or alternative control structure with + // T_END... missing. Either live coding, parse error or end + // tag in short open tags and scan run with short_open_tag=Off. + // Bow out completely as any further detection will be unreliable + // and create incorrect fixes or cause fixer conflicts. + return ($phpcsFile->numTokens + 1); + } + + unset($nextNonEmpty, $start); + + // This is a control structure without an opening brace, + // so it is an inline statement. + if ($this->error === true) { + $fix = $phpcsFile->addFixableError('Inline control structures are not allowed', $stackPtr, 'NotAllowed'); + } else { + $fix = $phpcsFile->addFixableWarning('Inline control structures are discouraged', $stackPtr, 'Discouraged'); + } + + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'yes'); + + // Stop here if we are not fixing the error. + if ($fix !== true) { + return; + } + + $phpcsFile->fixer->beginChangeset(); + if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) { + $closer = $tokens[$stackPtr]['parenthesis_closer']; + } else { + $closer = $stackPtr; + } + + if ($tokens[($closer + 1)]['code'] === T_WHITESPACE + || $tokens[($closer + 1)]['code'] === T_SEMICOLON + ) { + $phpcsFile->fixer->addContent($closer, ' {'); + } else { + $phpcsFile->fixer->addContent($closer, ' { '); + } + + $fixableScopeOpeners = $this->register(); + + $lastNonEmpty = $closer; + for ($end = ($closer + 1); $end < $phpcsFile->numTokens; $end++) { + if ($tokens[$end]['code'] === T_SEMICOLON) { + break; + } + + if ($tokens[$end]['code'] === T_CLOSE_TAG) { + $end = $lastNonEmpty; + break; + } + + if (in_array($tokens[$end]['code'], $fixableScopeOpeners, true) === true + && isset($tokens[$end]['scope_opener']) === false + ) { + // The best way to fix nested inline scopes is middle-out. + // So skip this one. It will be detected and fixed on a future loop. + $phpcsFile->fixer->rollbackChangeset(); + return; + } + + if (isset($tokens[$end]['scope_opener']) === true) { + $type = $tokens[$end]['code']; + $end = $tokens[$end]['scope_closer']; + if ($type === T_DO + || $type === T_IF || $type === T_ELSEIF + || $type === T_TRY || $type === T_CATCH || $type === T_FINALLY + ) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + if ($next === false) { + break; + } + + $nextType = $tokens[$next]['code']; + + // Let additional conditions loop and find their ending. + if (($type === T_IF + || $type === T_ELSEIF) + && ($nextType === T_ELSEIF + || $nextType === T_ELSE) + ) { + continue; + } + + // Account for TRY... CATCH/FINALLY statements. + if (($type === T_TRY + || $type === T_CATCH + || $type === T_FINALLY) + && ($nextType === T_CATCH + || $nextType === T_FINALLY) + ) { + continue; + } + + // Account for DO... WHILE conditions. + if ($type === T_DO && $nextType === T_WHILE) { + $end = $phpcsFile->findNext(T_SEMICOLON, ($next + 1)); + } + } else if ($type === T_CLOSURE) { + // There should be a semicolon after the closing brace. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + if ($next !== false && $tokens[$next]['code'] === T_SEMICOLON) { + $end = $next; + } + }//end if + + if ($tokens[$end]['code'] !== T_END_HEREDOC + && $tokens[$end]['code'] !== T_END_NOWDOC + ) { + break; + } + }//end if + + if (isset($tokens[$end]['parenthesis_closer']) === true) { + $end = $tokens[$end]['parenthesis_closer']; + $lastNonEmpty = $end; + continue; + } + + if ($tokens[$end]['code'] !== T_WHITESPACE) { + $lastNonEmpty = $end; + } + }//end for + + if ($end === $phpcsFile->numTokens) { + $end = $lastNonEmpty; + } + + $nextContent = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + if ($nextContent === false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Looks for completely empty statements. + $next = $phpcsFile->findNext(T_WHITESPACE, ($closer + 1), ($end + 1), true); + } else { + $next = ($end + 1); + $endLine = $end; + } + + if ($next !== $end) { + if ($nextContent === false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Account for a comment on the end of the line. + for ($endLine = $end; $endLine < $phpcsFile->numTokens; $endLine++) { + if (isset($tokens[($endLine + 1)]) === false + || $tokens[$endLine]['line'] !== $tokens[($endLine + 1)]['line'] + ) { + break; + } + } + + if (isset(Tokens::$commentTokens[$tokens[$endLine]['code']]) === false + && ($tokens[$endLine]['code'] !== T_WHITESPACE + || isset(Tokens::$commentTokens[$tokens[($endLine - 1)]['code']]) === false) + ) { + $endLine = $end; + } + } + + if ($endLine !== $end) { + $endToken = $endLine; + $addedContent = ''; + } else { + $endToken = $end; + $addedContent = $phpcsFile->eolChar; + + if ($tokens[$end]['code'] !== T_SEMICOLON + && $tokens[$end]['code'] !== T_CLOSE_CURLY_BRACKET + ) { + $phpcsFile->fixer->addContent($end, '; '); + } + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($endToken + 1), null, true); + if ($next !== false + && ($tokens[$next]['code'] === T_ELSE + || $tokens[$next]['code'] === T_ELSEIF) + ) { + $phpcsFile->fixer->addContentBefore($next, '} '); + } else { + $indent = ''; + for ($first = $stackPtr; $first > 0; $first--) { + if ($tokens[$first]['column'] === 1) { + break; + } + } + + if ($tokens[$first]['code'] === T_WHITESPACE) { + $indent = $tokens[$first]['content']; + } else if ($tokens[$first]['code'] === T_INLINE_HTML + || $tokens[$first]['code'] === T_OPEN_TAG + ) { + $addedContent = ''; + } + + $addedContent .= $indent.'}'; + if ($next !== false && $tokens[$endToken]['code'] === T_COMMENT) { + $addedContent .= $phpcsFile->eolChar; + } + + $phpcsFile->fixer->addContent($endToken, $addedContent); + }//end if + } else { + if ($nextContent === false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Account for a comment on the end of the line. + for ($endLine = $end; $endLine < $phpcsFile->numTokens; $endLine++) { + if (isset($tokens[($endLine + 1)]) === false + || $tokens[$endLine]['line'] !== $tokens[($endLine + 1)]['line'] + ) { + break; + } + } + + if ($tokens[$endLine]['code'] !== T_COMMENT + && ($tokens[$endLine]['code'] !== T_WHITESPACE + || $tokens[($endLine - 1)]['code'] !== T_COMMENT) + ) { + $endLine = $end; + } + } + + if ($endLine !== $end) { + $phpcsFile->fixer->replaceToken($end, ''); + $phpcsFile->fixer->addNewlineBefore($endLine); + $phpcsFile->fixer->addContent($endLine, '}'); + } else { + $phpcsFile->fixer->replaceToken($end, '}'); + } + }//end if + + $phpcsFile->fixer->endChangeset(); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php new file mode 100644 index 0000000..24028e5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php @@ -0,0 +1,96 @@ + + * @copyright 2013-2014 Roman Levishchenko + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class CSSLintSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $csslintPath = Config::getExecutablePath('csslint'); + if ($csslintPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + + $cmd = Common::escapeshellcmd($csslintPath).' '.escapeshellarg($fileName).' 2>&1'; + exec($cmd, $output, $retval); + + if (is_array($output) === false) { + return ($phpcsFile->numTokens + 1); + } + + $count = count($output); + + for ($i = 0; $i < $count; $i++) { + $matches = []; + $numMatches = preg_match( + '/(error|warning) at line (\d+)/', + $output[$i], + $matches + ); + + if ($numMatches === 0) { + continue; + } + + $line = (int) $matches[2]; + $message = 'csslint says: '.$output[($i + 1)]; + // First line is message with error line and error code. + // Second is error message. + // Third is wrong line in file. + // Fourth is empty line. + $i += 4; + + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool'); + }//end for + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php new file mode 100644 index 0000000..8b47983 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php @@ -0,0 +1,117 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class ClosureLinterSniff implements Sniff +{ + + /** + * A list of error codes that should show errors. + * + * All other error codes will show warnings. + * + * @var array + */ + public $errorCodes = []; + + /** + * A list of error codes to ignore. + * + * @var array + */ + public $ignoreCodes = []; + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jslint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $lintPath = Config::getExecutablePath('gjslint'); + if ($lintPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + + $lintPath = Common::escapeshellcmd($lintPath); + $cmd = $lintPath.' --nosummary --notime --unix_mode '.escapeshellarg($fileName); + exec($cmd, $output, $retval); + + if (is_array($output) === false) { + return ($phpcsFile->numTokens + 1); + } + + foreach ($output as $finding) { + $matches = []; + $numMatches = preg_match('/^(.*):([0-9]+):\(.*?([0-9]+)\)(.*)$/', $finding, $matches); + if ($numMatches === 0) { + continue; + } + + // Skip error codes we are ignoring. + $code = $matches[3]; + if (in_array($code, $this->ignoreCodes) === true) { + continue; + } + + $line = (int) $matches[2]; + $error = trim($matches[4]); + + $message = 'gjslint says: (%s) %s'; + $data = [ + $code, + $error, + ]; + if (in_array($code, $this->errorCodes) === true) { + $phpcsFile->addErrorOnLine($message, $line, 'ExternalToolError', $data); + } else { + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool', $data); + } + }//end foreach + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php new file mode 100644 index 0000000..004054d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php @@ -0,0 +1,113 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class ESLintSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + /** + * ESLint configuration file path. + * + * @var string|null Path to eslintrc. Null to autodetect. + */ + public $configFile = null; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jshint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $eslintPath = Config::getExecutablePath('eslint'); + if ($eslintPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $filename = $phpcsFile->getFilename(); + + $configFile = $this->configFile; + if (empty($configFile) === true) { + // Attempt to autodetect. + $candidates = glob('.eslintrc{.js,.yaml,.yml,.json}', GLOB_BRACE); + if (empty($candidates) === false) { + $configFile = $candidates[0]; + } + } + + $eslintOptions = ['--format json']; + if (empty($configFile) === false) { + $eslintOptions[] = '--config '.escapeshellarg($configFile); + } + + $cmd = Common::escapeshellcmd(escapeshellarg($eslintPath).' '.implode(' ', $eslintOptions).' '.escapeshellarg($filename)); + + // Execute! + exec($cmd, $stdout, $code); + + if ($code <= 0) { + // No errors, continue. + return ($phpcsFile->numTokens + 1); + } + + $data = json_decode(implode("\n", $stdout)); + if (json_last_error() !== JSON_ERROR_NONE) { + // Ignore any errors. + return ($phpcsFile->numTokens + 1); + } + + // Data is a list of files, but we only pass a single one. + $messages = $data[0]->messages; + foreach ($messages as $error) { + $message = 'eslint says: '.$error->message; + if (empty($error->fatal) === false || $error->severity === 2) { + $phpcsFile->addErrorOnLine($message, $error->line, 'ExternalTool'); + } else { + $phpcsFile->addWarningOnLine($message, $error->line, 'ExternalTool'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php new file mode 100644 index 0000000..1461d57 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php @@ -0,0 +1,95 @@ + + * @author Alexander Wei§ + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class JSHintSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jshint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $rhinoPath = Config::getExecutablePath('rhino'); + $jshintPath = Config::getExecutablePath('jshint'); + if ($jshintPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + $jshintPath = Common::escapeshellcmd($jshintPath); + + if ($rhinoPath !== null) { + $rhinoPath = Common::escapeshellcmd($rhinoPath); + $cmd = "$rhinoPath \"$jshintPath\" ".escapeshellarg($fileName); + exec($cmd, $output, $retval); + + $regex = '`^(?P.+)\(.+:(?P[0-9]+).*:[0-9]+\)$`'; + } else { + $cmd = "$jshintPath ".escapeshellarg($fileName); + exec($cmd, $output, $retval); + + $regex = '`^(.+?): line (?P[0-9]+), col [0-9]+, (?P.+)$`'; + } + + if (is_array($output) === true) { + foreach ($output as $finding) { + $matches = []; + $numMatches = preg_match($regex, $finding, $matches); + if ($numMatches === 0) { + continue; + } + + $line = (int) $matches['line']; + $message = 'jshint says: '.trim($matches['error']); + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php new file mode 100644 index 0000000..d014908 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php @@ -0,0 +1,80 @@ + + * @author Greg Sherwood + * @copyright 2010-2014 mediaSELF Sp. z o.o. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ByteOrderMarkSniff implements Sniff +{ + + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = [ + 'UTF-8' => 'efbbbf', + 'UTF-16 (BE)' => 'feff', + 'UTF-16 (LE)' => 'fffe', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INLINE_HTML]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // The BOM will be the very first token in the file. + if ($stackPtr !== 0) { + return; + } + + $tokens = $phpcsFile->getTokens(); + + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = (strlen($expectedBomHex) / 2); + $htmlBomHex = bin2hex(substr($tokens[$stackPtr]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex) { + $errorData = [$bomName]; + $error = 'File contains %s byte order mark, which may corrupt your application'; + $phpcsFile->addError($error, $stackPtr, 'Found', $errorData); + $phpcsFile->recordMetric($stackPtr, 'Using byte order mark', 'yes'); + return; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Using byte order mark', 'no'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php new file mode 100644 index 0000000..a920bdf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php @@ -0,0 +1,84 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class EndFileNewlineSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + 'CSS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + // Skip to the end of the file. + $tokens = $phpcsFile->getTokens(); + $stackPtr = ($phpcsFile->numTokens - 1); + + if ($tokens[$stackPtr]['content'] === '') { + $stackPtr--; + } + + $eolCharLen = strlen($phpcsFile->eolChar); + $lastChars = substr($tokens[$stackPtr]['content'], ($eolCharLen * -1)); + if ($lastChars !== $phpcsFile->eolChar) { + $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'no'); + + $error = 'File must end with a newline character'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotFound'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($stackPtr); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'yes'); + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php new file mode 100644 index 0000000..afff558 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class EndFileNoNewlineSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + 'CSS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + // Skip to the end of the file. + $tokens = $phpcsFile->getTokens(); + $stackPtr = ($phpcsFile->numTokens - 1); + + if ($tokens[$stackPtr]['content'] === '') { + --$stackPtr; + } + + $eolCharLen = strlen($phpcsFile->eolChar); + $lastChars = substr($tokens[$stackPtr]['content'], ($eolCharLen * -1)); + if ($lastChars === $phpcsFile->eolChar) { + $error = 'File must not end with a newline character'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = $stackPtr; $i > 0; $i--) { + $newContent = rtrim($tokens[$i]['content'], $phpcsFile->eolChar); + $phpcsFile->fixer->replaceToken($i, $newContent); + + if ($newContent !== '') { + break; + } + } + + $phpcsFile->fixer->endChangeset(); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php new file mode 100644 index 0000000..cb199aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php @@ -0,0 +1,62 @@ + + * @copyright 2019 Matthew Peveler + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ExecutableFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $filename = $phpcsFile->getFilename(); + + if ($filename !== 'STDIN') { + $perms = fileperms($phpcsFile->getFilename()); + if (($perms & 0x0040) !== 0 || ($perms & 0x0008) !== 0 || ($perms & 0x0001) !== 0) { + $error = 'A PHP file should not be executable; found file permissions set to %s'; + $data = [substr(sprintf('%o', $perms), -4)]; + $phpcsFile->addError($error, 0, 'Executable', $data); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php new file mode 100644 index 0000000..1d79a0e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php @@ -0,0 +1,79 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class InlineHTMLSniff implements Sniff +{ + + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = [ + 'UTF-8' => 'efbbbf', + 'UTF-16 (BE)' => 'feff', + 'UTF-16 (LE)' => 'fffe', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INLINE_HTML]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int|void + */ + public function process(File $phpcsFile, $stackPtr) + { + // Allow a byte-order mark. + $tokens = $phpcsFile->getTokens(); + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = (strlen($expectedBomHex) / 2); + $htmlBomHex = bin2hex(substr($tokens[0]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex && strlen($tokens[0]['content']) === $bomByteLength) { + return; + } + } + + // Ignore shebang lines. + $tokens = $phpcsFile->getTokens(); + if (substr($tokens[$stackPtr]['content'], 0, 2) === '#!') { + return; + } + + $error = 'PHP files must only contain PHP code'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + + return $phpcsFile->numTokens; + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php new file mode 100644 index 0000000..e44d514 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php @@ -0,0 +1,148 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class LineEndingsSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + 'CSS', + ]; + + /** + * The valid EOL character. + * + * @var string + */ + public $eolChar = '\n'; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $found = $phpcsFile->eolChar; + $found = str_replace("\n", '\n', $found); + $found = str_replace("\r", '\r', $found); + + $phpcsFile->recordMetric($stackPtr, 'EOL char', $found); + + if ($found === $this->eolChar) { + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + } + + // Check for single line files without an EOL. This is a very special + // case and the EOL char is set to \n when this happens. + if ($found === '\n') { + $tokens = $phpcsFile->getTokens(); + $lastToken = ($phpcsFile->numTokens - 1); + if ($tokens[$lastToken]['line'] === 1 + && $tokens[$lastToken]['content'] !== "\n" + ) { + return ($phpcsFile->numTokens + 1); + } + } + + $error = 'End of line character is invalid; expected "%s" but found "%s"'; + $expected = $this->eolChar; + $expected = str_replace("\n", '\n', $expected); + $expected = str_replace("\r", '\r', $expected); + $data = [ + $expected, + $found, + ]; + + // Errors are always reported on line 1, no matter where the first PHP tag is. + $fix = $phpcsFile->addFixableError($error, 0, 'InvalidEOLChar', $data); + + if ($fix === true) { + $tokens = $phpcsFile->getTokens(); + switch ($this->eolChar) { + case '\n': + $eolChar = "\n"; + break; + case '\r': + $eolChar = "\r"; + break; + case '\r\n': + $eolChar = "\r\n"; + break; + default: + $eolChar = $this->eolChar; + break; + } + + for ($i = 0; $i < $phpcsFile->numTokens; $i++) { + if (isset($tokens[($i + 1)]) === true + && $tokens[($i + 1)]['line'] <= $tokens[$i]['line'] + ) { + continue; + } + + // Token is the last on a line. + if (isset($tokens[$i]['orig_content']) === true) { + $tokenContent = $tokens[$i]['orig_content']; + } else { + $tokenContent = $tokens[$i]['content']; + } + + if ($tokenContent === '') { + // Special case for JS/CSS close tag. + continue; + } + + $newContent = rtrim($tokenContent, "\r\n"); + $newContent .= $eolChar; + if ($tokenContent !== $newContent) { + $phpcsFile->fixer->replaceToken($i, $newContent); + } + }//end for + }//end if + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php new file mode 100644 index 0000000..94d4144 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php @@ -0,0 +1,201 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class LineLengthSniff implements Sniff +{ + + /** + * The limit that the length of a line should not exceed. + * + * @var integer + */ + public $lineLimit = 80; + + /** + * The limit that the length of a line must not exceed. + * + * Set to zero (0) to disable. + * + * @var integer + */ + public $absoluteLineLimit = 100; + + /** + * Whether or not to ignore trailing comments. + * + * This has the effect of also ignoring all lines + * that only contain comments. + * + * @var boolean + */ + public $ignoreComments = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + for ($i = 1; $i < $phpcsFile->numTokens; $i++) { + if ($tokens[$i]['column'] === 1) { + $this->checkLineLength($phpcsFile, $tokens, $i); + } + } + + $this->checkLineLength($phpcsFile, $tokens, $i); + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + + /** + * Checks if a line is too long. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tokens The token stack. + * @param int $stackPtr The first token on the next line. + * + * @return void + */ + protected function checkLineLength($phpcsFile, $tokens, $stackPtr) + { + // The passed token is the first on the line. + $stackPtr--; + + if ($tokens[$stackPtr]['column'] === 1 + && $tokens[$stackPtr]['length'] === 0 + ) { + // Blank line. + return; + } + + if ($tokens[$stackPtr]['column'] !== 1 + && $tokens[$stackPtr]['content'] === $phpcsFile->eolChar + ) { + $stackPtr--; + } + + $onlyComment = false; + if (isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === true) { + $prevNonWhiteSpace = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$stackPtr]['line'] !== $tokens[$prevNonWhiteSpace]['line']) { + $onlyComment = true; + } + } + + if ($onlyComment === true + && isset(Tokens::$phpcsCommentTokens[$tokens[$stackPtr]['code']]) === true + ) { + // Ignore PHPCS annotation comments that are on a line by themselves. + return; + } + + $lineLength = ($tokens[$stackPtr]['column'] + $tokens[$stackPtr]['length'] - 1); + + if ($this->ignoreComments === true + && isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === true + ) { + // Trailing comments are being ignored in line length calculations. + if ($onlyComment === true) { + // The comment is the only thing on the line, so no need to check length. + return; + } + + $lineLength -= $tokens[$stackPtr]['length']; + } + + // Record metrics for common line length groupings. + if ($lineLength <= 80) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '80 or less'); + } else if ($lineLength <= 120) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '81-120'); + } else if ($lineLength <= 150) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '121-150'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Line length', '151 or more'); + } + + if ($onlyComment === true) { + // If this is a long comment, check if it can be broken up onto multiple lines. + // Some comments contain unbreakable strings like URLs and so it makes sense + // to ignore the line length in these cases if the URL would be longer than the max + // line length once you indent it to the correct level. + if ($lineLength > $this->lineLimit) { + $oldLength = strlen($tokens[$stackPtr]['content']); + $newLength = strlen(ltrim($tokens[$stackPtr]['content'], "/#\t ")); + $indent = (($tokens[$stackPtr]['column'] - 1) + ($oldLength - $newLength)); + + $nonBreakingLength = $tokens[$stackPtr]['length']; + + $space = strrpos($tokens[$stackPtr]['content'], ' '); + if ($space !== false) { + $nonBreakingLength -= ($space + 1); + } + + if (($nonBreakingLength + $indent) > $this->lineLimit) { + return; + } + } + }//end if + + if ($this->absoluteLineLimit > 0 + && $lineLength > $this->absoluteLineLimit + ) { + $data = [ + $this->absoluteLineLimit, + $lineLength, + ]; + + $error = 'Line exceeds maximum limit of %s characters; contains %s characters'; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else if ($lineLength > $this->lineLimit) { + $data = [ + $this->lineLimit, + $lineLength, + ]; + + $warning = 'Line exceeds %s characters; contains %s characters'; + $phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data); + } + + }//end checkLineLength() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php new file mode 100644 index 0000000..608fdcf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php @@ -0,0 +1,70 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class LowercasedFilenameSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $filename = $phpcsFile->getFilename(); + if ($filename === 'STDIN') { + return ($phpcsFile->numTokens + 1); + } + + $filename = basename($filename); + $lowercaseFilename = strtolower($filename); + if ($filename !== $lowercaseFilename) { + $data = [ + $filename, + $lowercaseFilename, + ]; + $error = 'Filename "%s" doesn\'t match the expected filename "%s"'; + $phpcsFile->addError($error, $stackPtr, 'NotFound', $data); + $phpcsFile->recordMetric($stackPtr, 'Lowercase filename', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Lowercase filename', 'yes'); + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php new file mode 100644 index 0000000..e328e74 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php @@ -0,0 +1,57 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OneClassPerFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLASS]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = ($stackPtr + 1); + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $start = ($tokens[$stackPtr]['scope_closer'] + 1); + } + + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== false) { + $error = 'Only one class is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php new file mode 100644 index 0000000..34211f2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php @@ -0,0 +1,57 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OneInterfacePerFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INTERFACE]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = ($stackPtr + 1); + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $start = ($tokens[$stackPtr]['scope_closer'] + 1); + } + + $nextInterface = $phpcsFile->findNext($this->register(), $start); + if ($nextInterface !== false) { + $error = 'Only one interface is allowed in a file'; + $phpcsFile->addError($error, $nextInterface, 'MultipleFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php new file mode 100644 index 0000000..459c5d1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OneObjectStructurePerFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = ($stackPtr + 1); + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $start = ($tokens[$stackPtr]['scope_closer'] + 1); + } + + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== false) { + $error = 'Only one object structure is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php new file mode 100644 index 0000000..309383f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php @@ -0,0 +1,57 @@ + + * @copyright 2010-2014 Alexander Obuhovich + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OneTraitPerFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_TRAIT]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = ($stackPtr + 1); + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $start = ($tokens[$stackPtr]['scope_closer'] + 1); + } + + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== false) { + $error = 'Only one trait is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php new file mode 100644 index 0000000..750fdab --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php @@ -0,0 +1,105 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowMultipleStatementsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_SEMICOLON]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $fixable = true; + $prev = $stackPtr; + + do { + $prev = $phpcsFile->findPrevious([T_SEMICOLON, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_PHPCS_IGNORE], ($prev - 1)); + if ($prev === false + || $tokens[$prev]['code'] === T_OPEN_TAG + || $tokens[$prev]['code'] === T_OPEN_TAG_WITH_ECHO + ) { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'no'); + return; + } + + if ($tokens[$prev]['code'] === T_PHPCS_IGNORE) { + $fixable = false; + } + } while ($tokens[$prev]['code'] === T_PHPCS_IGNORE); + + // Ignore multiple statements in a FOR condition. + foreach ([$stackPtr, $prev] as $checkToken) { + if (isset($tokens[$checkToken]['nested_parenthesis']) === true) { + foreach ($tokens[$checkToken]['nested_parenthesis'] as $bracket) { + if (isset($tokens[$bracket]['parenthesis_owner']) === false) { + // Probably a closure sitting inside a function call. + continue; + } + + $owner = $tokens[$bracket]['parenthesis_owner']; + if ($tokens[$owner]['code'] === T_FOR) { + return; + } + } + } + } + + if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']) { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'yes'); + + $error = 'Each PHP statement must be on a line by itself'; + $code = 'SameLine'; + if ($fixable === false) { + $phpcsFile->addError($error, $stackPtr, $code); + return; + } + + $fix = $phpcsFile->addFixableError($error, $stackPtr, $code); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($prev); + if ($tokens[($prev + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($prev + 1), ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'no'); + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php new file mode 100644 index 0000000..8916659 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php @@ -0,0 +1,426 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class MultipleStatementAlignmentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = false; + + /** + * The maximum amount of padding before the alignment is ignored. + * + * If the amount of padding required to align this assignment with the + * surrounding assignments exceeds this number, the assignment will be + * ignored and no errors or warnings will be thrown. + * + * @var integer + */ + public $maxPadding = 1000; + + /** + * Controls which side of the assignment token is used for alignment. + * + * @var boolean + */ + public $alignAtEnd = true; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $tokens = Tokens::$assignmentTokens; + unset($tokens[T_DOUBLE_ARROW]); + return $tokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $lastAssign = $this->checkAlignment($phpcsFile, $stackPtr); + return ($lastAssign + 1); + + }//end process() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $end The token where checking should end. + * If NULL, the entire file will be checked. + * + * @return int + */ + public function checkAlignment($phpcsFile, $stackPtr, $end=null) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore assignments used in a condition, like an IF or FOR or closure param defaults. + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + // If the parenthesis is on the same line as the assignment, + // then it should be ignored as it is specifically being grouped. + $parens = $tokens[$stackPtr]['nested_parenthesis']; + $lastParen = array_pop($parens); + if ($tokens[$lastParen]['line'] === $tokens[$stackPtr]['line']) { + return $stackPtr; + } + + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $start => $end) { + if (isset($tokens[$start]['parenthesis_owner']) === true) { + return $stackPtr; + } + } + } + + $assignments = []; + $prevAssign = null; + $lastLine = $tokens[$stackPtr]['line']; + $maxPadding = null; + $stopped = null; + $lastCode = $stackPtr; + $lastSemi = null; + $arrayEnd = null; + + if ($end === null) { + $end = $phpcsFile->numTokens; + } + + $find = Tokens::$assignmentTokens; + unset($find[T_DOUBLE_ARROW]); + + $scopes = Tokens::$scopeOpeners; + unset($scopes[T_CLOSURE]); + unset($scopes[T_ANON_CLASS]); + unset($scopes[T_OBJECT]); + + for ($assign = $stackPtr; $assign < $end; $assign++) { + if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // Statement is in a different context, so the block is over. + break; + } + + if (isset($tokens[$assign]['scope_opener']) === true + && $tokens[$assign]['level'] === $tokens[$stackPtr]['level'] + ) { + if (isset($scopes[$tokens[$assign]['code']]) === true) { + // This type of scope indicates that the assignment block is over. + break; + } + + // Skip over the scope block because it is seen as part of the assignment block, + // but also process any assignment blocks that are inside as well. + $nextAssign = $phpcsFile->findNext($find, ($assign + 1), ($tokens[$assign]['scope_closer'] - 1)); + if ($nextAssign !== false) { + $assign = $this->checkAlignment($phpcsFile, $nextAssign); + } else { + $assign = $tokens[$assign]['scope_closer']; + } + + $lastCode = $assign; + continue; + } + + if ($assign === $arrayEnd) { + $arrayEnd = null; + } + + if (isset($find[$tokens[$assign]['code']]) === false) { + // A blank line indicates that the assignment block has ended. + if (isset(Tokens::$emptyTokens[$tokens[$assign]['code']]) === false + && ($tokens[$assign]['line'] - $tokens[$lastCode]['line']) > 1 + && $tokens[$assign]['level'] === $tokens[$stackPtr]['level'] + && $arrayEnd === null + ) { + break; + } + + if ($tokens[$assign]['code'] === T_CLOSE_TAG) { + // Breaking out of PHP ends the assignment block. + break; + } + + if ($tokens[$assign]['code'] === T_OPEN_SHORT_ARRAY + && isset($tokens[$assign]['bracket_closer']) === true + ) { + $arrayEnd = $tokens[$assign]['bracket_closer']; + } + + if ($tokens[$assign]['code'] === T_ARRAY + && isset($tokens[$assign]['parenthesis_opener']) === true + && isset($tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer']) === true + ) { + $arrayEnd = $tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer']; + } + + if (isset(Tokens::$emptyTokens[$tokens[$assign]['code']]) === false) { + $lastCode = $assign; + + if ($tokens[$assign]['code'] === T_SEMICOLON) { + if ($tokens[$assign]['conditions'] === $tokens[$stackPtr]['conditions']) { + if ($lastSemi !== null && $prevAssign !== null && $lastSemi > $prevAssign) { + // This statement did not have an assignment operator in it. + break; + } else { + $lastSemi = $assign; + } + } else if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // Statement is in a different context, so the block is over. + break; + } + } + }//end if + + continue; + } else if ($assign !== $stackPtr && $tokens[$assign]['line'] === $lastLine) { + // Skip multiple assignments on the same line. We only need to + // try and align the first assignment. + continue; + }//end if + + if ($assign !== $stackPtr) { + if ($tokens[$assign]['level'] > $tokens[$stackPtr]['level']) { + // Has to be nested inside the same conditions as the first assignment. + // We've gone one level down, so process this new block. + $assign = $this->checkAlignment($phpcsFile, $assign); + $lastCode = $assign; + continue; + } else if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // We've gone one level up, so the block we are processing is done. + break; + } else if ($arrayEnd !== null) { + // Assignments inside arrays are not part of + // the original block, so process this new block. + $assign = ($this->checkAlignment($phpcsFile, $assign, $arrayEnd) - 1); + $arrayEnd = null; + $lastCode = $assign; + continue; + } + + // Make sure it is not assigned inside a condition (eg. IF, FOR). + if (isset($tokens[$assign]['nested_parenthesis']) === true) { + // If the parenthesis is on the same line as the assignment, + // then it should be ignored as it is specifically being grouped. + $parens = $tokens[$assign]['nested_parenthesis']; + $lastParen = array_pop($parens); + if ($tokens[$lastParen]['line'] === $tokens[$assign]['line']) { + break; + } + + foreach ($tokens[$assign]['nested_parenthesis'] as $start => $end) { + if (isset($tokens[$start]['parenthesis_owner']) === true) { + break(2); + } + } + } + }//end if + + $var = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($assign - 1), + null, + true + ); + + // Make sure we wouldn't break our max padding length if we + // aligned with this statement, or they wouldn't break the max + // padding length if they aligned with us. + $varEnd = $tokens[($var + 1)]['column']; + $assignLen = $tokens[$assign]['length']; + if ($this->alignAtEnd !== true) { + $assignLen = 1; + } + + if ($assign !== $stackPtr) { + if ($prevAssign === null) { + // Processing an inner block but no assignments found. + break; + } + + if (($varEnd + 1) > $assignments[$prevAssign]['assign_col']) { + $padding = 1; + $assignColumn = ($varEnd + 1); + } else { + $padding = ($assignments[$prevAssign]['assign_col'] - $varEnd + $assignments[$prevAssign]['assign_len'] - $assignLen); + if ($padding <= 0) { + $padding = 1; + } + + if ($padding > $this->maxPadding) { + $stopped = $assign; + break; + } + + $assignColumn = ($varEnd + $padding); + }//end if + + if (($assignColumn + $assignLen) > ($assignments[$maxPadding]['assign_col'] + $assignments[$maxPadding]['assign_len'])) { + $newPadding = ($varEnd - $assignments[$maxPadding]['var_end'] + $assignLen - $assignments[$maxPadding]['assign_len'] + 1); + if ($newPadding > $this->maxPadding) { + $stopped = $assign; + break; + } else { + // New alignment settings for previous assignments. + foreach ($assignments as $i => $data) { + if ($i === $assign) { + break; + } + + $newPadding = ($varEnd - $data['var_end'] + $assignLen - $data['assign_len'] + 1); + $assignments[$i]['expected'] = $newPadding; + $assignments[$i]['assign_col'] = ($data['var_end'] + $newPadding); + } + + $padding = 1; + $assignColumn = ($varEnd + 1); + } + } else if ($padding > $assignments[$maxPadding]['expected']) { + $maxPadding = $assign; + }//end if + } else { + $padding = 1; + $assignColumn = ($varEnd + 1); + $maxPadding = $assign; + }//end if + + $found = 0; + if ($tokens[($var + 1)]['code'] === T_WHITESPACE) { + $found = $tokens[($var + 1)]['length']; + if ($found === 0) { + // This means a newline was found. + $found = 1; + } + } + + $assignments[$assign] = [ + 'var_end' => $varEnd, + 'assign_len' => $assignLen, + 'assign_col' => $assignColumn, + 'expected' => $padding, + 'found' => $found, + ]; + + $lastLine = $tokens[$assign]['line']; + $prevAssign = $assign; + }//end for + + if (empty($assignments) === true) { + return $stackPtr; + } + + $numAssignments = count($assignments); + + $errorGenerated = false; + foreach ($assignments as $assignment => $data) { + if ($data['found'] === $data['expected']) { + continue; + } + + $expectedText = $data['expected'].' space'; + if ($data['expected'] !== 1) { + $expectedText .= 's'; + } + + if ($data['found'] === null) { + $foundText = 'a new line'; + } else { + $foundText = $data['found'].' space'; + if ($data['found'] !== 1) { + $foundText .= 's'; + } + } + + if ($numAssignments === 1) { + $type = 'Incorrect'; + $error = 'Equals sign not aligned correctly; expected %s but found %s'; + } else { + $type = 'NotSame'; + $error = 'Equals sign not aligned with surrounding assignments; expected %s but found %s'; + } + + $errorData = [ + $expectedText, + $foundText, + ]; + + if ($this->error === true) { + $fix = $phpcsFile->addFixableError($error, $assignment, $type, $errorData); + } else { + $fix = $phpcsFile->addFixableWarning($error, $assignment, $type.'Warning', $errorData); + } + + $errorGenerated = true; + + if ($fix === true && $data['found'] !== null) { + $newContent = str_repeat(' ', $data['expected']); + if ($data['found'] === 0) { + $phpcsFile->fixer->addContentBefore($assignment, $newContent); + } else { + $phpcsFile->fixer->replaceToken(($assignment - 1), $newContent); + } + } + }//end foreach + + if ($numAssignments > 1) { + if ($errorGenerated === true) { + $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'yes'); + } + } + + if ($stopped !== null) { + return $this->checkAlignment($phpcsFile, $stopped); + } else { + return $assign; + } + + }//end checkAlignment() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php new file mode 100644 index 0000000..f7644df --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * + * @deprecated 3.4.0 Use the Generic.Formatting.SpaceAfterCast sniff with + * the $spacing property set to 0 instead. + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class NoSpaceAfterCastSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + return; + } + + $error = 'A cast statement must not be followed by a space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceFound'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php new file mode 100644 index 0000000..d831ea7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php @@ -0,0 +1,161 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SpaceAfterCastSniff implements Sniff +{ + + /** + * The number of spaces desired after a cast token. + * + * @var integer + */ + public $spacing = 1; + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $this->spacing = (int) $this->spacing; + $pluralizeSpace = 's'; + if ($this->spacing === 1) { + $pluralizeSpace = ''; + } + + if ($tokens[$stackPtr]['code'] === T_BINARY_CAST + && $tokens[$stackPtr]['content'] === 'b' + ) { + // You can't replace a space after this type of binary casting. + return; + } + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($nextNonEmpty === false) { + return; + } + + if ($this->ignoreNewlines === true + && $tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line'] + ) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 'newline'); + return; + } + + if ($this->spacing === 0 && $nextNonEmpty === ($stackPtr + 1)) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 0); + return; + } + + $nextNonWhitespace = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($nextNonEmpty !== $nextNonWhitespace) { + $error = 'Expected %s space%s after cast statement; comment found'; + $data = [ + $this->spacing, + $pluralizeSpace, + ]; + $phpcsFile->addError($error, $stackPtr, 'CommentFound', $data); + + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', $tokens[($stackPtr + 1)]['length']); + } else { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 0); + } + + return; + } + + $found = 0; + if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $found = 'newline'; + } else if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $found = $tokens[($stackPtr + 1)]['length']; + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', $found); + + if ($found === $this->spacing) { + return; + } + + $error = 'Expected %s space%s after cast statement; %s found'; + $data = [ + $this->spacing, + $pluralizeSpace, + $found, + ]; + + $errorCode = 'TooMuchSpace'; + if ($this->spacing !== 0) { + if ($found === 0) { + $errorCode = 'NoSpace'; + } else if ($found !== 'newline' && $found < $this->spacing) { + $errorCode = 'TooLittleSpace'; + } + } + + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data); + + if ($fix === true) { + $padding = str_repeat(' ', $this->spacing); + if ($found === 0) { + $phpcsFile->fixer->addContent($stackPtr, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $start = ($stackPtr + 1); + + if ($this->spacing > 0) { + $phpcsFile->fixer->replaceToken($start, $padding); + ++$start; + } + + for ($i = $start; $i < $nextNonWhitespace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php new file mode 100644 index 0000000..a1a6d09 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php @@ -0,0 +1,143 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SpaceAfterNotSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The number of spaces desired after the NOT operator. + * + * @var integer + */ + public $spacing = 1; + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_BOOLEAN_NOT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $this->spacing = (int) $this->spacing; + $pluralizeSpace = 's'; + if ($this->spacing === 1) { + $pluralizeSpace = ''; + } + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($nextNonEmpty === false) { + return; + } + + if ($this->ignoreNewlines === true + && $tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line'] + ) { + return; + } + + if ($this->spacing === 0 && $nextNonEmpty === ($stackPtr + 1)) { + return; + } + + $nextNonWhitespace = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($nextNonEmpty !== $nextNonWhitespace) { + $error = 'Expected %s space%s after NOT operator; comment found'; + $data = [ + $this->spacing, + $pluralizeSpace, + ]; + $phpcsFile->addError($error, $stackPtr, 'CommentFound', $data); + return; + } + + $found = 0; + if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $found = 'newline'; + } else if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $found = $tokens[($stackPtr + 1)]['length']; + } + + if ($found === $this->spacing) { + return; + } + + $error = 'Expected %s space%s after NOT operator; %s found'; + $data = [ + $this->spacing, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Incorrect', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->spacing); + if ($found === 0) { + $phpcsFile->fixer->addContent($stackPtr, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $start = ($stackPtr + 1); + + if ($this->spacing > 0) { + $phpcsFile->fixer->replaceToken($start, $padding); + ++$start; + } + + for ($i = $start; $i < $nextNonWhitespace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php new file mode 100644 index 0000000..96082e3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php @@ -0,0 +1,73 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SpaceBeforeCastSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['column'] === 1) { + return; + } + + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $error = 'A cast statement must be preceded by a single space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpace'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing before cast statement', 0); + return; + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing before cast statement', $tokens[($stackPtr - 1)]['length']); + + if ($tokens[($stackPtr - 1)]['column'] !== 1 && $tokens[($stackPtr - 1)]['length'] !== 1) { + $error = 'A cast statement must be preceded by a single space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'TooMuchSpace'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php new file mode 100644 index 0000000..d97c0f7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php @@ -0,0 +1,141 @@ + + * @copyright 2009-2014 Florian Grandel + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class CallTimePassByReferenceSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_STRING, + T_VARIABLE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $findTokens = Tokens::$emptyTokens; + $findTokens[] = T_BITWISE_AND; + + $prev = $phpcsFile->findPrevious($findTokens, ($stackPtr - 1), null, true); + + // Skip tokens that are the names of functions or classes + // within their definitions. For example: function myFunction... + // "myFunction" is T_STRING but we should skip because it is not a + // function or method *call*. + $prevCode = $tokens[$prev]['code']; + if ($prevCode === T_FUNCTION || $prevCode === T_CLASS) { + return; + } + + // If the next non-whitespace token after the function or method call + // is not an opening parenthesis then it cant really be a *call*. + $functionName = $stackPtr; + $openBracket = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($functionName + 1), + null, + true + ); + + if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) { + return; + } + + if (isset($tokens[$openBracket]['parenthesis_closer']) === false) { + return; + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + $nextSeparator = $openBracket; + $find = [ + T_VARIABLE, + T_OPEN_SHORT_ARRAY, + ]; + + while (($nextSeparator = $phpcsFile->findNext($find, ($nextSeparator + 1), $closeBracket)) !== false) { + if (isset($tokens[$nextSeparator]['nested_parenthesis']) === false) { + continue; + } + + if ($tokens[$nextSeparator]['code'] === T_OPEN_SHORT_ARRAY) { + $nextSeparator = $tokens[$nextSeparator]['bracket_closer']; + continue; + } + + // Make sure the variable belongs directly to this function call + // and is not inside a nested function call or array. + $brackets = $tokens[$nextSeparator]['nested_parenthesis']; + $lastBracket = array_pop($brackets); + if ($lastBracket !== $closeBracket) { + continue; + } + + $tokenBefore = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($nextSeparator - 1), + null, + true + ); + + if ($tokens[$tokenBefore]['code'] === T_BITWISE_AND) { + if ($phpcsFile->isReference($tokenBefore) === false) { + continue; + } + + // We also want to ignore references used in assignment + // operations passed as function arguments, but isReference() + // sees them as valid references (which they are). + $tokenBefore = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($tokenBefore - 1), + null, + true + ); + + if (isset(Tokens::$assignmentTokens[$tokens[$tokenBefore]['code']]) === true) { + continue; + } + + // T_BITWISE_AND represents a pass-by-reference. + $error = 'Call-time pass-by-reference calls are prohibited'; + $phpcsFile->addError($error, $tokenBefore, 'NotAllowed'); + }//end if + }//end while + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php new file mode 100644 index 0000000..1ae4822 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php @@ -0,0 +1,189 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionCallArgumentSpacingSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return[ + T_STRING, + T_ISSET, + T_UNSET, + T_SELF, + T_STATIC, + T_PARENT, + T_VARIABLE, + T_CLOSE_CURLY_BRACKET, + T_CLOSE_PARENTHESIS, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Skip tokens that are the names of functions or classes + // within their definitions. For example: + // function myFunction... + // "myFunction" is T_STRING but we should skip because it is not a + // function or method *call*. + $functionName = $stackPtr; + $ignoreTokens = Tokens::$emptyTokens; + $ignoreTokens[] = T_BITWISE_AND; + $functionKeyword = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true); + if ($tokens[$functionKeyword]['code'] === T_FUNCTION || $tokens[$functionKeyword]['code'] === T_CLASS) { + return; + } + + if ($tokens[$stackPtr]['code'] === T_CLOSE_CURLY_BRACKET + && isset($tokens[$stackPtr]['scope_condition']) === true + ) { + // Not a function call. + return; + } + + // If the next non-whitespace token after the function or method call + // is not an opening parenthesis then it can't really be a *call*. + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, ($functionName + 1), null, true); + if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) { + return; + } + + if (isset($tokens[$openBracket]['parenthesis_closer']) === false) { + return; + } + + $this->checkSpacing($phpcsFile, $stackPtr, $openBracket); + + }//end process() + + + /** + * Checks the spacing around commas. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * + * @return void + */ + public function checkSpacing(File $phpcsFile, $stackPtr, $openBracket) + { + $tokens = $phpcsFile->getTokens(); + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + $nextSeparator = $openBracket; + + $find = [ + T_COMMA, + T_CLOSURE, + T_ANON_CLASS, + T_OPEN_SHORT_ARRAY, + ]; + + while (($nextSeparator = $phpcsFile->findNext($find, ($nextSeparator + 1), $closeBracket)) !== false) { + if ($tokens[$nextSeparator]['code'] === T_CLOSURE + || $tokens[$nextSeparator]['code'] === T_ANON_CLASS + ) { + // Skip closures. + $nextSeparator = $tokens[$nextSeparator]['scope_closer']; + continue; + } else if ($tokens[$nextSeparator]['code'] === T_OPEN_SHORT_ARRAY) { + // Skips arrays using short notation. + $nextSeparator = $tokens[$nextSeparator]['bracket_closer']; + continue; + } + + // Make sure the comma or variable belongs directly to this function call, + // and is not inside a nested function call or array. + $brackets = $tokens[$nextSeparator]['nested_parenthesis']; + $lastBracket = array_pop($brackets); + if ($lastBracket !== $closeBracket) { + continue; + } + + if ($tokens[$nextSeparator]['code'] === T_COMMA) { + if ($tokens[($nextSeparator - 1)]['code'] === T_WHITESPACE) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($nextSeparator - 2), null, true); + if (isset(Tokens::$heredocTokens[$tokens[$prev]['code']]) === false) { + $error = 'Space found before comma in argument list'; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'SpaceBeforeComma'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + if ($tokens[$prev]['line'] !== $tokens[$nextSeparator]['line']) { + $phpcsFile->fixer->addContent($prev, ','); + $phpcsFile->fixer->replaceToken($nextSeparator, ''); + } else { + $phpcsFile->fixer->replaceToken(($nextSeparator - 1), ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + if ($tokens[($nextSeparator + 1)]['code'] !== T_WHITESPACE) { + // Ignore trailing comma's after last argument as that's outside the scope of this sniff. + if (($nextSeparator + 1) !== $closeBracket) { + $error = 'No space found after comma in argument list'; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'NoSpaceAfterComma'); + if ($fix === true) { + $phpcsFile->fixer->addContent($nextSeparator, ' '); + } + } + } else { + // If there is a newline in the space, then they must be formatting + // each argument on a newline, which is valid, so ignore it. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextSeparator + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$nextSeparator]['line']) { + $space = $tokens[($nextSeparator + 1)]['length']; + if ($space > 1) { + $error = 'Expected 1 space after comma in argument list; %s found'; + $data = [$space]; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'TooMuchSpaceAfterComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($nextSeparator + 1), ' '); + } + } + } + }//end if + }//end if + }//end while + + }//end checkSpacing() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php new file mode 100644 index 0000000..be96f58 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php @@ -0,0 +1,225 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OpeningFunctionBraceBsdAllmanSniff implements Sniff +{ + + /** + * Should this sniff check function braces? + * + * @var boolean + */ + public $checkFunctions = true; + + /** + * Should this sniff check closure braces? + * + * @var boolean + */ + public $checkClosures = false; + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + if (($tokens[$stackPtr]['code'] === T_FUNCTION + && (bool) $this->checkFunctions === false) + || ($tokens[$stackPtr]['code'] === T_CLOSURE + && (bool) $this->checkClosures === false) + ) { + return; + } + + $openingBrace = $tokens[$stackPtr]['scope_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + } + } + + // Find the end of the function declaration. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($openingBrace - 1), $closeBracket, true); + + $functionLine = $tokens[$prev]['line']; + $braceLine = $tokens[$openingBrace]['line']; + + $lineDifference = ($braceLine - $functionLine); + + $metricType = 'Function'; + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $metricType = 'Closure'; + } + + if ($lineDifference === 0) { + $error = 'Opening brace should be on a new line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnSameLine'); + if ($fix === true) { + $hasTrailingAnnotation = false; + for ($nextLine = ($openingBrace + 1); $nextLine < $phpcsFile->numTokens; $nextLine++) { + if ($tokens[$openingBrace]['line'] !== $tokens[$nextLine]['line']) { + break; + } + + if (isset(Tokens::$phpcsCommentTokens[$tokens[$nextLine]['code']]) === true) { + $hasTrailingAnnotation = true; + } + } + + $phpcsFile->fixer->beginChangeset(); + $indent = $phpcsFile->findFirstOnLine([], $openingBrace); + + if ($hasTrailingAnnotation === false || $nextLine === false) { + if ($tokens[$indent]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->addContentBefore($openingBrace, $tokens[$indent]['content']); + } + + if ($tokens[($openingBrace - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($openingBrace - 1), ''); + } + + $phpcsFile->fixer->addNewlineBefore($openingBrace); + } else { + $phpcsFile->fixer->replaceToken($openingBrace, ''); + $phpcsFile->fixer->addNewlineBefore($nextLine); + $phpcsFile->fixer->addContentBefore($nextLine, '{'); + + if ($tokens[$indent]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->addContentBefore($nextLine, $tokens[$indent]['content']); + } + } + + $phpcsFile->fixer->endChangeset(); + }//end if + + $phpcsFile->recordMetric($stackPtr, "$metricType opening brace placement", 'same line'); + } else if ($lineDifference > 1) { + $error = 'Opening brace should be on the line after the declaration; found %s blank line(s)'; + $data = [($lineDifference - 1)]; + + $prevNonWs = $phpcsFile->findPrevious(T_WHITESPACE, ($openingBrace - 1), $closeBracket, true); + if ($prevNonWs !== $prev) { + // There must be a comment between the end of the function declaration and the open brace. + // Report, but don't fix. + $phpcsFile->addError($error, $openingBrace, 'BraceSpacing', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceSpacing', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $openingBrace; $i > $prev; $i--) { + if ($tokens[$i]['line'] === $tokens[$openingBrace]['line']) { + if ($tokens[$i]['column'] === 1) { + $phpcsFile->fixer->addNewLineBefore($i); + } + + continue; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + $ignore = Tokens::$phpcsCommentTokens; + $ignore[] = T_WHITESPACE; + $next = $phpcsFile->findNext($ignore, ($openingBrace + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + // Only throw this error when this is not an empty function. + if ($next !== $tokens[$stackPtr]['scope_closer']) { + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + } + + // Only continue checking if the opening brace looks good. + if ($lineDifference !== 1) { + return; + } + + // We need to actually find the first piece of content on this line, + // as if this is a method with tokens before it (public, static etc) + // or an if with an else before it, then we need to start the scope + // checking from there, rather than the current token. + $lineStart = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + + // The opening brace is on the correct line, now it needs to be + // checked to be correctly indented. + $startColumn = $tokens[$lineStart]['column']; + $braceIndent = $tokens[$openingBrace]['column']; + + if ($braceIndent !== $startColumn) { + $expected = ($startColumn - 1); + $found = ($braceIndent - 1); + + $error = 'Opening brace indented incorrectly; expected %s spaces, found %s'; + $data = [ + $expected, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceIndent', $data); + if ($fix === true) { + $indent = str_repeat(' ', $expected); + if ($found === 0) { + $phpcsFile->fixer->addContentBefore($openingBrace, $indent); + } else { + $phpcsFile->fixer->replaceToken(($openingBrace - 1), $indent); + } + } + }//end if + + $phpcsFile->recordMetric($stackPtr, "$metricType opening brace placement", 'new line'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php new file mode 100644 index 0000000..ca25985 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php @@ -0,0 +1,182 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OpeningFunctionBraceKernighanRitchieSniff implements Sniff +{ + + /** + * Should this sniff check function braces? + * + * @var boolean + */ + public $checkFunctions = true; + + /** + * Should this sniff check closure braces? + * + * @var boolean + */ + public $checkClosures = false; + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + if (($tokens[$stackPtr]['code'] === T_FUNCTION + && (bool) $this->checkFunctions === false) + || ($tokens[$stackPtr]['code'] === T_CLOSURE + && (bool) $this->checkClosures === false) + ) { + return; + } + + $openingBrace = $tokens[$stackPtr]['scope_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + } + } + + // Find the end of the function declaration. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($openingBrace - 1), $closeBracket, true); + + $functionLine = $tokens[$prev]['line']; + $braceLine = $tokens[$openingBrace]['line']; + + $lineDifference = ($braceLine - $functionLine); + + $metricType = 'Function'; + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $metricType = 'Closure'; + } + + if ($lineDifference > 0) { + $phpcsFile->recordMetric($stackPtr, "$metricType opening brace placement", 'new line'); + $error = 'Opening brace should be on the same line as the declaration'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnNewLine'); + if ($fix === true) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($openingBrace - 1), $closeBracket, true); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($prev, ' {'); + $phpcsFile->fixer->replaceToken($openingBrace, ''); + if ($tokens[($openingBrace + 1)]['code'] === T_WHITESPACE + && $tokens[($openingBrace + 2)]['line'] > $tokens[$openingBrace]['line'] + ) { + // Brace is followed by a new line, so remove it to ensure we don't + // leave behind a blank line at the top of the block. + $phpcsFile->fixer->replaceToken(($openingBrace + 1), ''); + + if ($tokens[($openingBrace - 1)]['code'] === T_WHITESPACE + && $tokens[($openingBrace - 1)]['line'] === $tokens[$openingBrace]['line'] + && $tokens[($openingBrace - 2)]['line'] < $tokens[$openingBrace]['line'] + ) { + // Brace is preceded by indent, so remove it to ensure we don't + // leave behind more indent than is required for the first line. + $phpcsFile->fixer->replaceToken(($openingBrace - 1), ''); + } + } + + $phpcsFile->fixer->endChangeset(); + }//end if + } else { + $phpcsFile->recordMetric($stackPtr, "$metricType opening brace placement", 'same line'); + }//end if + + $ignore = Tokens::$phpcsCommentTokens; + $ignore[] = T_WHITESPACE; + $next = $phpcsFile->findNext($ignore, ($openingBrace + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + // Only throw this error when this is not an empty function. + if ($next !== $tokens[$stackPtr]['scope_closer'] + && $tokens[$next]['code'] !== T_CLOSE_TAG + ) { + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + } + + // Only continue checking if the opening brace looks good. + if ($lineDifference > 0) { + return; + } + + // We are looking for tabs, even if they have been replaced, because + // we enforce a space here. + if (isset($tokens[($openingBrace - 1)]['orig_content']) === true) { + $spacing = $tokens[($openingBrace - 1)]['orig_content']; + } else { + $spacing = $tokens[($openingBrace - 1)]['content']; + } + + if ($tokens[($openingBrace - 1)]['code'] !== T_WHITESPACE) { + $length = 0; + } else if ($spacing === "\t") { + $length = '\t'; + } else { + $length = strlen($spacing); + } + + if ($length !== 1) { + $error = 'Expected 1 space before opening brace; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'SpaceBeforeBrace', $data); + if ($fix === true) { + if ($length === 0 || $length === '\t') { + $phpcsFile->fixer->addContentBefore($openingBrace, ' '); + } else { + $phpcsFile->fixer->replaceToken(($openingBrace - 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php new file mode 100644 index 0000000..8cba81d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php @@ -0,0 +1,117 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Mayflower GmbH + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class CyclomaticComplexitySniff implements Sniff +{ + + /** + * A complexity higher than this value will throw a warning. + * + * @var integer + */ + public $complexity = 10; + + /** + * A complexity higher than this value will throw an error. + * + * @var integer + */ + public $absoluteComplexity = 20; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore abstract methods. + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + // Detect start and end of this function definition. + $start = $tokens[$stackPtr]['scope_opener']; + $end = $tokens[$stackPtr]['scope_closer']; + + // Predicate nodes for PHP. + $find = [ + T_CASE => true, + T_DEFAULT => true, + T_CATCH => true, + T_IF => true, + T_FOR => true, + T_FOREACH => true, + T_WHILE => true, + T_ELSEIF => true, + T_INLINE_THEN => true, + T_COALESCE => true, + T_COALESCE_EQUAL => true, + T_MATCH_ARROW => true, + T_NULLSAFE_OBJECT_OPERATOR => true, + ]; + + $complexity = 1; + + // Iterate from start to end and count predicate nodes. + for ($i = ($start + 1); $i < $end; $i++) { + if (isset($find[$tokens[$i]['code']]) === true) { + $complexity++; + } + } + + if ($complexity > $this->absoluteComplexity) { + $error = 'Function\'s cyclomatic complexity (%s) exceeds allowed maximum of %s'; + $data = [ + $complexity, + $this->absoluteComplexity, + ]; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else if ($complexity > $this->complexity) { + $warning = 'Function\'s cyclomatic complexity (%s) exceeds %s; consider refactoring the function'; + $data = [ + $complexity, + $this->complexity, + ]; + $phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php new file mode 100644 index 0000000..3c086c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php @@ -0,0 +1,100 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Mayflower GmbH + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class NestingLevelSniff implements Sniff +{ + + /** + * A nesting level higher than this value will throw a warning. + * + * @var integer + */ + public $nestingLevel = 5; + + /** + * A nesting level higher than this value will throw an error. + * + * @var integer + */ + public $absoluteNestingLevel = 10; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore abstract methods. + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + // Detect start and end of this function definition. + $start = $tokens[$stackPtr]['scope_opener']; + $end = $tokens[$stackPtr]['scope_closer']; + + $nestingLevel = 0; + + // Find the maximum nesting level of any token in the function. + for ($i = ($start + 1); $i < $end; $i++) { + $level = $tokens[$i]['level']; + if ($nestingLevel < $level) { + $nestingLevel = $level; + } + } + + // We subtract the nesting level of the function itself. + $nestingLevel = ($nestingLevel - $tokens[$stackPtr]['level'] - 1); + + if ($nestingLevel > $this->absoluteNestingLevel) { + $error = 'Function\'s nesting level (%s) exceeds allowed maximum of %s'; + $data = [ + $nestingLevel, + $this->absoluteNestingLevel, + ]; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else if ($nestingLevel > $this->nestingLevel) { + $warning = 'Function\'s nesting level (%s) exceeds %s; consider refactoring the function'; + $data = [ + $nestingLevel, + $this->nestingLevel, + ]; + $phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php new file mode 100644 index 0000000..145dddf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php @@ -0,0 +1,60 @@ + + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class AbstractClassNamePrefixSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLASS]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($phpcsFile->getClassProperties($stackPtr)['is_abstract'] === false) { + // This class is not abstract so we don't need to check it. + return; + } + + $className = $phpcsFile->getDeclarationName($stackPtr); + if ($className === null) { + // We are not interested in anonymous classes. + return; + } + + $prefix = substr($className, 0, 8); + if (strtolower($prefix) !== 'abstract') { + $phpcsFile->addError('Abstract class names must be prefixed with "Abstract"; found "%s"', $stackPtr, 'Missing', [$className]); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php new file mode 100644 index 0000000..ec1cfd0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php @@ -0,0 +1,223 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Tokens; + +class CamelCapsFunctionNameSniff extends AbstractScopeSniff +{ + + /** + * A list of all PHP magic methods. + * + * @var array + */ + protected $magicMethods = [ + 'construct' => true, + 'destruct' => true, + 'call' => true, + 'callstatic' => true, + 'get' => true, + 'set' => true, + 'isset' => true, + 'unset' => true, + 'sleep' => true, + 'wakeup' => true, + 'serialize' => true, + 'unserialize' => true, + 'tostring' => true, + 'invoke' => true, + 'set_state' => true, + 'clone' => true, + 'debuginfo' => true, + ]; + + /** + * A list of all PHP non-magic methods starting with a double underscore. + * + * These come from PHP modules such as SOAPClient. + * + * @var array + */ + protected $methodsDoubleUnderscore = [ + 'dorequest' => true, + 'getcookies' => true, + 'getfunctions' => true, + 'getlastrequest' => true, + 'getlastrequestheaders' => true, + 'getlastresponse' => true, + 'getlastresponseheaders' => true, + 'gettypes' => true, + 'setcookie' => true, + 'setlocation' => true, + 'setsoapheaders' => true, + 'soapcall' => true, + ]; + + /** + * A list of all PHP magic functions. + * + * @var array + */ + protected $magicFunctions = ['autoload' => true]; + + /** + * If TRUE, the string must not have two capital letters next to each other. + * + * @var boolean + */ + public $strict = true; + + + /** + * Constructs a Generic_Sniffs_NamingConventions_CamelCapsFunctionNameSniff. + */ + public function __construct() + { + parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION], true); + + }//end __construct() + + + /** + * Processes the tokens within the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * @param int $currScope The position of the current scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + + $className = $phpcsFile->getDeclarationName($currScope); + if (isset($className) === false) { + $className = '[Anonymous Class]'; + } + + $errorData = [$className.'::'.$methodName]; + + $methodNameLc = strtolower($methodName); + $classNameLc = strtolower($className); + + // Is this a magic method. i.e., is prefixed with "__" ? + if (preg_match('|^__[^_]|', $methodName) !== 0) { + $magicPart = substr($methodNameLc, 2); + if (isset($this->magicMethods[$magicPart]) === true + || isset($this->methodsDoubleUnderscore[$magicPart]) === true + ) { + return; + } + + $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'MethodDoubleUnderscore', $errorData); + } + + // PHP4 constructors are allowed to break our rules. + if ($methodNameLc === $classNameLc) { + return; + } + + // PHP4 destructors are allowed to break our rules. + if ($methodNameLc === '_'.$classNameLc) { + return; + } + + // Ignore first underscore in methods prefixed with "_". + $methodName = ltrim($methodName, '_'); + + $methodProps = $phpcsFile->getMethodProperties($stackPtr); + if (Common::isCamelCaps($methodName, false, true, $this->strict) === false) { + if ($methodProps['scope_specified'] === true) { + $error = '%s method name "%s" is not in camel caps format'; + $data = [ + ucfirst($methodProps['scope']), + $errorData[0], + ]; + $phpcsFile->addError($error, $stackPtr, 'ScopeNotCamelCaps', $data); + } else { + $error = 'Method name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + } + + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'no'); + return; + } else { + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'yes'); + } + + }//end processTokenWithinScope() + + + /** + * Processes the tokens outside the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $functionName = $phpcsFile->getDeclarationName($stackPtr); + if ($functionName === null) { + // Ignore closures. + return; + } + + $errorData = [$functionName]; + + // Is this a magic function. i.e., it is prefixed with "__". + if (preg_match('|^__[^_]|', $functionName) !== 0) { + $magicPart = strtolower(substr($functionName, 2)); + if (isset($this->magicFunctions[$magicPart]) === true) { + return; + } + + $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'FunctionDoubleUnderscore', $errorData); + } + + // Ignore first underscore in functions prefixed with "_". + $functionName = ltrim($functionName, '_'); + + if (Common::isCamelCaps($functionName, false, true, $this->strict) === false) { + $error = 'Function name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + $phpcsFile->recordMetric($stackPtr, 'CamelCase function name', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'yes'); + } + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php new file mode 100644 index 0000000..75fbd22 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php @@ -0,0 +1,163 @@ + + * @author Leif Wickland + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; + +class ConstructorNameSniff extends AbstractScopeSniff +{ + + /** + * The name of the class we are currently checking. + * + * @var string + */ + private $currentClass = ''; + + /** + * A list of functions in the current class. + * + * @var string[] + */ + private $functionList = []; + + + /** + * Constructs the test with the tokens it wishes to listen for. + */ + public function __construct() + { + parent::__construct([T_CLASS, T_ANON_CLASS], [T_FUNCTION], true); + + }//end __construct() + + + /** + * Processes this test when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $currScope A pointer to the start of the scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $className = $phpcsFile->getDeclarationName($currScope); + if (empty($className) === false) { + // Not an anonymous class. + $className = strtolower($className); + } + + if ($className !== $this->currentClass) { + $this->loadFunctionNamesInScope($phpcsFile, $currScope); + $this->currentClass = $className; + } + + $methodName = strtolower($phpcsFile->getDeclarationName($stackPtr)); + + if ($methodName === $className) { + if (in_array('__construct', $this->functionList, true) === false) { + $error = 'PHP4 style constructors are not allowed; use "__construct()" instead'; + $phpcsFile->addError($error, $stackPtr, 'OldStyle'); + } + } else if ($methodName !== '__construct') { + // Not a constructor. + return; + } + + // Stop if the constructor doesn't have a body, like when it is abstract. + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $parentClassName = strtolower($phpcsFile->findExtendedClassName($currScope)); + if ($parentClassName === false) { + return; + } + + $endFunctionIndex = $tokens[$stackPtr]['scope_closer']; + $startIndex = $stackPtr; + while (($doubleColonIndex = $phpcsFile->findNext(T_DOUBLE_COLON, $startIndex, $endFunctionIndex)) !== false) { + if ($tokens[($doubleColonIndex + 1)]['code'] === T_STRING + && strtolower($tokens[($doubleColonIndex + 1)]['content']) === $parentClassName + ) { + $error = 'PHP4 style calls to parent constructors are not allowed; use "parent::__construct()" instead'; + $phpcsFile->addError($error, ($doubleColonIndex + 1), 'OldStyleCall'); + } + + $startIndex = ($doubleColonIndex + 1); + } + + }//end processTokenWithinScope() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + + /** + * Extracts all the function names found in the given scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $currScope A pointer to the start of the scope. + * + * @return void + */ + protected function loadFunctionNamesInScope(File $phpcsFile, $currScope) + { + $this->functionList = []; + $tokens = $phpcsFile->getTokens(); + + for ($i = ($tokens[$currScope]['scope_opener'] + 1); $i < $tokens[$currScope]['scope_closer']; $i++) { + if ($tokens[$i]['code'] !== T_FUNCTION) { + continue; + } + + $this->functionList[] = trim(strtolower($phpcsFile->getDeclarationName($i))); + + if (isset($tokens[$i]['scope_closer']) !== false) { + // Skip past nested functions and such. + $i = $tokens[$i]['scope_closer']; + } + } + + }//end loadFunctionNamesInScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php new file mode 100644 index 0000000..637e036 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php @@ -0,0 +1,54 @@ + + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class InterfaceNameSuffixSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INTERFACE]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $interfaceName = $phpcsFile->getDeclarationName($stackPtr); + if ($interfaceName === null) { + return; + } + + $suffix = substr($interfaceName, -9); + if (strtolower($suffix) !== 'interface') { + $phpcsFile->addError('Interface names must be suffixed with "Interface"; found "%s"', $stackPtr, 'Missing', [$interfaceName]); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php new file mode 100644 index 0000000..cbd9651 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php @@ -0,0 +1,54 @@ + + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class TraitNameSuffixSniff implements Sniff +{ + + + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return array + */ + public function register() + { + return [T_TRAIT]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $traitName = $phpcsFile->getDeclarationName($stackPtr); + if ($traitName === null) { + return; + } + + $suffix = substr($traitName, -5); + if (strtolower($suffix) !== 'trait') { + $phpcsFile->addError('Trait names must be suffixed with "Trait"; found "%s"', $stackPtr, 'Missing', [$traitName]); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php new file mode 100644 index 0000000..1373d3b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php @@ -0,0 +1,141 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UpperCaseConstantNameSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_STRING, + T_CONST, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_CONST) { + // This is a class constant. + $constant = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($constant === false) { + return; + } + + $constName = $tokens[$constant]['content']; + + if (strtoupper($constName) !== $constName) { + if (strtolower($constName) === $constName) { + $phpcsFile->recordMetric($constant, 'Constant name case', 'lower'); + } else { + $phpcsFile->recordMetric($constant, 'Constant name case', 'mixed'); + } + + $error = 'Class constants must be uppercase; expected %s but found %s'; + $data = [ + strtoupper($constName), + $constName, + ]; + $phpcsFile->addError($error, $constant, 'ClassConstantNotUpperCase', $data); + } else { + $phpcsFile->recordMetric($constant, 'Constant name case', 'upper'); + } + + return; + }//end if + + // Only interested in define statements now. + if (strtolower($tokens[$stackPtr]['content']) !== 'define') { + return; + } + + // Make sure this is not a method call. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] === T_OBJECT_OPERATOR + || $tokens[$prev]['code'] === T_DOUBLE_COLON + || $tokens[$prev]['code'] === T_NULLSAFE_OBJECT_OPERATOR + ) { + return; + } + + // If the next non-whitespace token after this token + // is not an opening parenthesis then it is not a function call. + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($openBracket === false) { + return; + } + + // The next non-whitespace token must be the constant name. + $constPtr = $phpcsFile->findNext(T_WHITESPACE, ($openBracket + 1), null, true); + if ($tokens[$constPtr]['code'] !== T_CONSTANT_ENCAPSED_STRING) { + return; + } + + $constName = $tokens[$constPtr]['content']; + + // Check for constants like self::CONSTANT. + $prefix = ''; + $splitPos = strpos($constName, '::'); + if ($splitPos !== false) { + $prefix = substr($constName, 0, ($splitPos + 2)); + $constName = substr($constName, ($splitPos + 2)); + } + + // Strip namespace from constant like /foo/bar/CONSTANT. + $splitPos = strrpos($constName, '\\'); + if ($splitPos !== false) { + $prefix = substr($constName, 0, ($splitPos + 1)); + $constName = substr($constName, ($splitPos + 1)); + } + + if (strtoupper($constName) !== $constName) { + if (strtolower($constName) === $constName) { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'lower'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'mixed'); + } + + $error = 'Constants must be uppercase; expected %s but found %s'; + $data = [ + $prefix.strtoupper($constName), + $prefix.$constName, + ]; + $phpcsFile->addError($error, $stackPtr, 'ConstantNotUpperCase', $data); + } else { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'upper'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php new file mode 100644 index 0000000..f3c56b5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php @@ -0,0 +1,48 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class BacktickOperatorSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_BACKTICK]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $error = 'Use of the backtick operator is forbidden'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php new file mode 100644 index 0000000..66f7386 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php @@ -0,0 +1,86 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class CharacterBeforePHPOpeningTagSniff implements Sniff +{ + + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = [ + 'UTF-8' => 'efbbbf', + 'UTF-16 (BE)' => 'feff', + 'UTF-16 (LE)' => 'fffe', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $expected = 0; + if ($stackPtr > 0) { + // Allow a byte-order mark. + $tokens = $phpcsFile->getTokens(); + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = (strlen($expectedBomHex) / 2); + $htmlBomHex = bin2hex(substr($tokens[0]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex) { + $expected++; + break; + } + } + + // Allow a shebang line. + if (substr($tokens[0]['content'], 0, 2) === '#!') { + $expected++; + } + } + + if ($stackPtr !== $expected) { + $error = 'The opening PHP tag must be the first content in the file'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + + // Skip the rest of the file so we don't pick up additional + // open tags, typically embedded in HTML. + return $phpcsFile->numTokens; + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php new file mode 100644 index 0000000..23dd2b6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php @@ -0,0 +1,54 @@ + + * @copyright 2010-2014 Stefano Kowalke + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClosingPHPTagSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $closeTag = $phpcsFile->findNext(T_CLOSE_TAG, $stackPtr); + if ($closeTag === false) { + $error = 'The PHP open tag does not have a corresponding PHP close tag'; + $phpcsFile->addError($error, $stackPtr, 'NotFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php new file mode 100644 index 0000000..83f3889 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php @@ -0,0 +1,73 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +class DeprecatedFunctionsSniff extends ForbiddenFunctionsSniff +{ + + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. IE, the + * function should just not be used. + * + * @var array + */ + public $forbiddenFunctions = []; + + + /** + * Constructor. + * + * Uses the Reflection API to get a list of deprecated functions. + */ + public function __construct() + { + $functions = get_defined_functions(); + + foreach ($functions['internal'] as $functionName) { + $function = new \ReflectionFunction($functionName); + + if ($function->isDeprecated() === true) { + $this->forbiddenFunctions[$functionName] = null; + } + } + + }//end __construct() + + + /** + * Generates the error or warning for this sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the forbidden function + * in the token array. + * @param string $function The name of the forbidden function. + * @param string $pattern The pattern used for the match. + * + * @return void + */ + protected function addError($phpcsFile, $stackPtr, $function, $pattern=null) + { + $data = [$function]; + $error = 'Function %s() has been deprecated'; + $type = 'Deprecated'; + + if ($this->error === true) { + $phpcsFile->addError($error, $stackPtr, $type, $data); + } else { + $phpcsFile->addWarning($error, $stackPtr, $type, $data); + } + + }//end addError() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php new file mode 100644 index 0000000..a2cf1b9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php @@ -0,0 +1,253 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowAlternativePHPTagsSniff implements Sniff +{ + + /** + * Whether ASP tags are enabled or not. + * + * @var boolean + */ + private $aspTags = false; + + /** + * The current PHP version. + * + * @var integer|string|null + */ + private $phpVersion = null; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + if ($this->phpVersion === null) { + $this->phpVersion = Config::getConfigData('php_version'); + if ($this->phpVersion === null) { + $this->phpVersion = PHP_VERSION_ID; + } + } + + if ($this->phpVersion < 70000) { + $this->aspTags = (bool) ini_get('asp_tags'); + } + + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + T_INLINE_HTML, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $openTag = $tokens[$stackPtr]; + $content = $openTag['content']; + + if (trim($content) === '') { + return; + } + + if ($openTag['code'] === T_OPEN_TAG) { + if ($content === '<%') { + $error = 'ASP style opening tag used; expected "findClosingTag($phpcsFile, $tokens, $stackPtr, '%>'); + $errorCode = 'ASPOpenTagFound'; + } else if (strpos($content, ''); + $errorCode = 'ScriptOpenTagFound'; + } + + if (isset($error, $closer, $errorCode) === true) { + $data = [$content]; + + if ($closer === false) { + $phpcsFile->addError($error, $stackPtr, $errorCode, $data); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data); + if ($fix === true) { + $this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer); + } + } + } + + return; + }//end if + + if ($openTag['code'] === T_OPEN_TAG_WITH_ECHO && $content === '<%=') { + $error = 'ASP style opening tag used with echo; expected "findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $snippet = $this->getSnippet($tokens[$nextVar]['content']); + $data = [ + $snippet, + $content, + $snippet, + ]; + + $closer = $this->findClosingTag($phpcsFile, $tokens, $stackPtr, '%>'); + + if ($closer === false) { + $phpcsFile->addError($error, $stackPtr, 'ASPShortOpenTagFound', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ASPShortOpenTagFound', $data); + if ($fix === true) { + $this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer, true); + } + } + + return; + }//end if + + // Account for incorrect script open tags. + if ($openTag['code'] === T_INLINE_HTML + && preg_match('`( + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.1.inc.fixed new file mode 100644 index 0000000..2a695c8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.1.inc.fixed @@ -0,0 +1,14 @@ +
+ +Some content here. + + + + +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc new file mode 100644 index 0000000..cd5a662 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc @@ -0,0 +1,6 @@ +
+<% echo $var; %> +

Some text <% echo $var; %> and some more text

+<%= $var . ' and some more text to make sure the snippet works'; %> +

Some text <%= $var %> and some more text

+
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc.fixed new file mode 100644 index 0000000..6eafb42 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.2.inc.fixed @@ -0,0 +1,6 @@ +
+ +

Some text and some more text

+ +

Some text and some more text

+
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.3.inc new file mode 100644 index 0000000..ba86345 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.3.inc @@ -0,0 +1,7 @@ + +
+<% echo $var; %> +

Some text <% echo $var; %> and some more text

+<%= $var . ' and some more text to make sure the snippet works'; %> +

Some text <%= $var %> and some more text

+
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php new file mode 100644 index 0000000..212f08a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowAlternativePHPTagsUnitTest.php @@ -0,0 +1,110 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowAlternativePHPTags sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DisallowAlternativePHPTagsSniff + */ +class DisallowAlternativePHPTagsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of all test files to check. + * + * @param string $testFileBase The base path that the unit tests files will have. + * + * @return string[] + */ + protected function getTestFiles($testFileBase) + { + $testFiles = [$testFileBase.'1.inc']; + + $aspTags = false; + if (PHP_VERSION_ID < 70000) { + $aspTags = (bool) ini_get('asp_tags'); + } + + if ($aspTags === true) { + $testFiles[] = $testFileBase.'2.inc'; + } else { + $testFiles[] = $testFileBase.'3.inc'; + } + + return $testFiles; + + }//end getTestFiles() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowAlternativePHPTagsUnitTest.1.inc': + return [ + 4 => 1, + 7 => 1, + 8 => 1, + 11 => 1, + ]; + case 'DisallowAlternativePHPTagsUnitTest.2.inc': + return [ + 2 => 1, + 3 => 1, + 4 => 1, + 5 => 1, + ]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + if ($testFile === 'DisallowAlternativePHPTagsUnitTest.3.inc') { + return [ + 3 => 1, + 4 => 1, + 5 => 1, + 6 => 1, + ]; + } + + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.inc new file mode 100644 index 0000000..974e45c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.inc @@ -0,0 +1,16 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.php new file mode 100644 index 0000000..b54405e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowRequestSuperglobalUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowRequestSuperglobal sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DisallowRequestSuperglobalSniff + */ +class DisallowRequestSuperglobalUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + protected function getErrorList() + { + return [ + 2 => 1, + 12 => 1, + 13 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + protected function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc new file mode 100644 index 0000000..040e62d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc @@ -0,0 +1,11 @@ +
+ +Some content here. + + +Some content Some more content + + +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc.fixed new file mode 100644 index 0000000..1ea281a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.1.inc.fixed @@ -0,0 +1,11 @@ +
+ +Some content here. + + +Some content Some more content + + +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc new file mode 100644 index 0000000..85617de --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc @@ -0,0 +1,8 @@ +
+ +Some content Some more content + + +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc.fixed new file mode 100644 index 0000000..afe5d8f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.2.inc.fixed @@ -0,0 +1,8 @@ +
+ +Some content Some more content + + +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.3.inc new file mode 100644 index 0000000..9b7ccd6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DisallowShortOpenTagUnitTest.3.inc @@ -0,0 +1,16 @@ +// Test warning for when short_open_tag is off. + +Some content Some more content + +// Test multi-line. +Some content Some more content + +// Make sure skipping works. +Some content Some more content + +// Only recognize closing tag after opener. +Some?> content + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowShortOpenTag sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DisallowShortOpenTagSniff + */ +class DisallowShortOpenTagUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of all test files to check. + * + * @param string $testFileBase The base path that the unit tests files will have. + * + * @return string[] + */ + protected function getTestFiles($testFileBase) + { + $testFiles = [$testFileBase.'1.inc']; + + $option = (bool) ini_get('short_open_tag'); + if ($option === true) { + $testFiles[] = $testFileBase.'2.inc'; + } else { + $testFiles[] = $testFileBase.'3.inc'; + } + + return $testFiles; + + }//end getTestFiles() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowShortOpenTagUnitTest.1.inc': + return [ + 5 => 1, + 6 => 1, + 7 => 1, + 10 => 1, + ]; + case 'DisallowShortOpenTagUnitTest.2.inc': + return [ + 2 => 1, + 3 => 1, + 4 => 1, + 7 => 1, + ]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'DisallowShortOpenTagUnitTest.1.inc': + return []; + case 'DisallowShortOpenTagUnitTest.3.inc': + return [ + 3 => 1, + 6 => 1, + 11 => 1, + ]; + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DiscourageGotoUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DiscourageGotoUnitTest.inc new file mode 100644 index 0000000..f564215 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/DiscourageGotoUnitTest.inc @@ -0,0 +1,18 @@ + + * @copyright 2006-2017 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DiscourageGoto sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DiscourageGotoSniff + */ +class DiscourageGotoUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 3 => 1, + 6 => 1, + 11 => 1, + 16 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.inc new file mode 100644 index 0000000..060da61 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.inc @@ -0,0 +1,60 @@ +sizeof($array); +$size = $class->count($array); +$class->delete($filepath); +$class->unset($filepath); + +function delete() {} +function unset() {} +function sizeof() {} +function count() {} + +trait DelProvider { + public function delete() { + //irrelevant + } +} + +class LeftSideTest { + use DelProvider { + delete as protected unsetter; + } +} + +class RightSideTest { + use DelProvider { + delete as delete; + } +} + +class RightSideVisTest { + use DelProvider { + delete as protected delete; + DelProvider::delete insteadof delete; + } +} + +namespace Something\sizeof; +$var = new Sizeof(); +class SizeOf implements Something {} + +function mymodule_form_callback(SizeOf $sizeof) { +} + +$size = $class?->sizeof($array); + +#[SizeOf(10)] +function doSomething() {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.php new file mode 100644 index 0000000..06be9d7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/ForbiddenFunctionsUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ForbiddenFunctions sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff + */ +class ForbiddenFunctionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + $errors = [ + 2 => 1, + 4 => 1, + 6 => 1, + ]; + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc new file mode 100644 index 0000000..5dfb755 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc @@ -0,0 +1,149 @@ +NULL = 7; + +use Zend\Log\Writer\NULL as NullWriter; +new \Zend\Log\Writer\NULL(); + +namespace False; + +class True extends Null implements False {} + +use True\Something; +use Something\True; +class MyClass +{ + public function myFunction() + { + $var = array('foo' => new True()); + } +} + +$x = $f?FALSE:true; +$x = $f? FALSE:true; + +class MyClass +{ + // Spice things up a little. + const TRUE = false; +} + +var_dump(MyClass::TRUE); + +function tRUE() {} + +$input->getFilterChain()->attachByName('Null', ['type' => Null::TYPE_STRING]); + +// Issue #3332 - ignore type declarations, but not default values. +class TypedThings { + const MYCONST = FALSE; + + public int|FALSE $int = FALSE; + public Type|NULL $int = new MyObj(NULL); + + private function typed(int|FALSE $param = NULL, Type|NULL $obj = new MyObj(FALSE)) : string|FALSE|NULL + { + if (TRUE === FALSE) { + return NULL; + } + } +} + +$cl = function (int|FALSE $param = NULL, Type|NULL $obj = new MyObj(FALSE)) : string|FALSE|NULL {}; + +// Adding some extra tests to safeguard that function declarations which don't create scope are handled correctly. +interface InterfaceMethodsWithReturnTypeNoScopeOpener { + private function typed($param = TRUE) : string|FALSE|NULL; +} + +abstract class ClassMethodsWithReturnTypeNoScopeOpener { + abstract public function typed($param = FALSE) : TRUE; +} + +// Additional tests to safeguard improved property type skip logic. +readonly class Properties { + use SomeTrait { + sayHello as private myPrivateHello; + } + + public Type|FALSE|NULL $propertyA = array( + 'itemA' => TRUE, + 'itemB' => FALSE, + 'itemC' => NULL, + ), $propertyB = FALSE; + + protected \FullyQualified&Partially\Qualified&namespace\Relative $propertyC; + var ?TRUE $propertyD; + static array|callable|FALSE|self|parent $propertyE = TRUE; + private + // phpcs:ignore Stnd.Cat.Sniff -- for reasons. + TRUE /*comment*/ + $propertyF = TRUE; + + public function __construct( + public FALSE|NULL $promotedPropA, + readonly callable|TRUE $promotedPropB, + ) { + static $var; + echo static::class; + static::foo(); + $var = $var instanceof static; + $obj = new static(); + } + + public static function foo(): static|self|FALSE { + $callable = static function() {}; + } +} + +// Last coding/parse error. +// This has to be the last test in the file. +function UnclosedCurly (): FALSE { diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc.fixed new file mode 100644 index 0000000..6b999cc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.inc.fixed @@ -0,0 +1,149 @@ +NULL = 7; + +use Zend\Log\Writer\NULL as NullWriter; +new \Zend\Log\Writer\NULL(); + +namespace False; + +class True extends Null implements False {} + +use True\Something; +use Something\True; +class MyClass +{ + public function myFunction() + { + $var = array('foo' => new True()); + } +} + +$x = $f?false:true; +$x = $f? false:true; + +class MyClass +{ + // Spice things up a little. + const TRUE = false; +} + +var_dump(MyClass::TRUE); + +function tRUE() {} + +$input->getFilterChain()->attachByName('Null', ['type' => Null::TYPE_STRING]); + +// Issue #3332 - ignore type declarations, but not default values. +class TypedThings { + const MYCONST = false; + + public int|FALSE $int = false; + public Type|NULL $int = new MyObj(null); + + private function typed(int|FALSE $param = null, Type|NULL $obj = new MyObj(false)) : string|FALSE|NULL + { + if (true === false) { + return null; + } + } +} + +$cl = function (int|FALSE $param = null, Type|NULL $obj = new MyObj(false)) : string|FALSE|NULL {}; + +// Adding some extra tests to safeguard that function declarations which don't create scope are handled correctly. +interface InterfaceMethodsWithReturnTypeNoScopeOpener { + private function typed($param = true) : string|FALSE|NULL; +} + +abstract class ClassMethodsWithReturnTypeNoScopeOpener { + abstract public function typed($param = false) : TRUE; +} + +// Additional tests to safeguard improved property type skip logic. +readonly class Properties { + use SomeTrait { + sayHello as private myPrivateHello; + } + + public Type|FALSE|NULL $propertyA = array( + 'itemA' => true, + 'itemB' => false, + 'itemC' => null, + ), $propertyB = false; + + protected \FullyQualified&Partially\Qualified&namespace\Relative $propertyC; + var ?TRUE $propertyD; + static array|callable|FALSE|self|parent $propertyE = true; + private + // phpcs:ignore Stnd.Cat.Sniff -- for reasons. + TRUE /*comment*/ + $propertyF = true; + + public function __construct( + public FALSE|NULL $promotedPropA, + readonly callable|TRUE $promotedPropB, + ) { + static $var; + echo static::class; + static::foo(); + $var = $var instanceof static; + $obj = new static(); + } + + public static function foo(): static|self|FALSE { + $callable = static function() {}; + } +} + +// Last coding/parse error. +// This has to be the last test in the file. +function UnclosedCurly (): FALSE { diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js new file mode 100644 index 0000000..87cfb82 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js @@ -0,0 +1,14 @@ +if (variable === true) { } +if (variable === TRUE) { } +if (variable === True) { } +variable = True; + +if (variable === false) { } +if (variable === FALSE) { } +if (variable === False) { } +variable = false; + +if (variable === null) { } +if (variable === NULL) { } +if (variable === Null) { } +variable = NULL; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js.fixed new file mode 100644 index 0000000..7dbf3ad --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.js.fixed @@ -0,0 +1,14 @@ +if (variable === true) { } +if (variable === true) { } +if (variable === true) { } +variable = true; + +if (variable === false) { } +if (variable === false) { } +if (variable === false) { } +variable = false; + +if (variable === null) { } +if (variable === null) { } +if (variable === null) { } +variable = null; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.php new file mode 100644 index 0000000..fac155c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseConstantUnitTest.php @@ -0,0 +1,103 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowerCaseConstant sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\LowerCaseConstantSniff + */ +class LowerCaseConstantUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'LowerCaseConstantUnitTest.inc': + return [ + 7 => 1, + 10 => 1, + 15 => 1, + 16 => 1, + 23 => 1, + 26 => 1, + 31 => 1, + 32 => 1, + 39 => 1, + 42 => 1, + 47 => 1, + 48 => 1, + 70 => 1, + 71 => 1, + 87 => 1, + 89 => 1, + 90 => 1, + 92 => 2, + 94 => 2, + 95 => 1, + 100 => 2, + 104 => 1, + 108 => 1, + 118 => 1, + 119 => 1, + 120 => 1, + 121 => 1, + 125 => 1, + 129 => 1, + ]; + + case 'LowerCaseConstantUnitTest.js': + return [ + 2 => 1, + 3 => 1, + 4 => 1, + 7 => 1, + 8 => 1, + 12 => 1, + 13 => 1, + 14 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc new file mode 100644 index 0000000..37579d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc @@ -0,0 +1,48 @@ + $x; +$r = Match ($x) { + 1 => 1, + 2 => 2, + DEFAULT, => 3, +}; + +class Reading { + Public READOnly int $var; +} + +EnuM ENUM: string +{ + Case HEARTS; +} + +__HALT_COMPILER(); // An exception due to phar support. +function diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc.fixed new file mode 100644 index 0000000..7063327 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.inc.fixed @@ -0,0 +1,48 @@ + $x; +$r = match ($x) { + 1 => 1, + 2 => 2, + default, => 3, +}; + +class Reading { + public readonly int $var; +} + +enum ENUM: string +{ + case HEARTS; +} + +__HALT_COMPILER(); // An exception due to phar support. +function diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.php new file mode 100644 index 0000000..a7b708e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseKeywordUnitTest.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowerCaseKeyword sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\LowerCaseKeywordSniff + */ +class LowerCaseKeywordUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 10 => 3, + 11 => 4, + 12 => 1, + 13 => 3, + 14 => 7, + 15 => 1, + 19 => 1, + 20 => 1, + 21 => 1, + 25 => 1, + 28 => 1, + 31 => 1, + 32 => 1, + 35 => 1, + 39 => 2, + 42 => 1, + 44 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc new file mode 100644 index 0000000..56393c0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc @@ -0,0 +1,101 @@ + $a * $b; +$arrow = fn (Int $a, String $b, BOOL $c, Array $d, Foo\Bar $e) : Float => $a * $b; + +$cl = function (False $a, TRUE $b, Null $c): ?True {}; + +// Intentional error, should be ignored by the sniff. +interface PropertiesNotAllowed { + public $notAllowed; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc.fixed new file mode 100644 index 0000000..c1055c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.inc.fixed @@ -0,0 +1,101 @@ + $a * $b; +$arrow = fn (int $a, string $b, bool $c, array $d, Foo\Bar $e) : float => $a * $b; + +$cl = function (false $a, true $b, null $c): ?true {}; + +// Intentional error, should be ignored by the sniff. +interface PropertiesNotAllowed { + public $notAllowed; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.php new file mode 100644 index 0000000..4e6ccc3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/LowerCaseTypeUnitTest.php @@ -0,0 +1,97 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowerCaseType sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\LowerCaseTypeSniff + */ +class LowerCaseTypeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 14 => 1, + 15 => 1, + 16 => 1, + 17 => 1, + 18 => 1, + 21 => 4, + 22 => 3, + 23 => 3, + 25 => 1, + 26 => 2, + 27 => 2, + 32 => 4, + 36 => 1, + 37 => 1, + 38 => 1, + 39 => 1, + 43 => 2, + 44 => 1, + 46 => 1, + 49 => 1, + 51 => 2, + 53 => 1, + 55 => 2, + 60 => 1, + 61 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 71 => 3, + 72 => 2, + 73 => 3, + 74 => 3, + 78 => 3, + 82 => 2, + 85 => 1, + 94 => 5, + 96 => 4, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + // Warning from getMemberProperties() about parse error. + return [100 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/NoSilencedErrorsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/NoSilencedErrorsUnitTest.inc new file mode 100644 index 0000000..98159b4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/NoSilencedErrorsUnitTest.inc @@ -0,0 +1,16 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the NoSilencedErrors sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\NoSilencedErrorsSniff + */ +class NoSilencedErrorsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [13 => 1]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 5 => 1, + 10 => 1, + 16 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/RequireStrictTypesUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/RequireStrictTypesUnitTest.1.inc new file mode 100644 index 0000000..387cec2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/RequireStrictTypesUnitTest.1.inc @@ -0,0 +1,8 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the RequireStrictType sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\RequireStrictTypesSniff + */ +class RequireStrictTypesUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'RequireStrictTypesUnitTest.2.inc': + case 'RequireStrictTypesUnitTest.5.inc': + case 'RequireStrictTypesUnitTest.6.inc': + case 'RequireStrictTypesUnitTest.10.inc': + return [1 => 1]; + + default: + return []; + } + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'RequireStrictTypesUnitTest.11.inc': + case 'RequireStrictTypesUnitTest.12.inc': + case 'RequireStrictTypesUnitTest.14.inc': + case 'RequireStrictTypesUnitTest.15.inc': + return [3 => 1]; + + default: + return []; + } + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.inc new file mode 100644 index 0000000..f0f350f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.inc @@ -0,0 +1,5 @@ +php_sapi_name() === true) {} +if ($object?->php_sapi_name() === true) {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.php new file mode 100644 index 0000000..9835b06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SAPIUsageUnitTest.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SAPIUsage sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\SAPIUsageSniff + */ +class SAPIUsageUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [2 => 1]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.1.inc new file mode 100644 index 0000000..4f0d9d8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.1.inc @@ -0,0 +1,4 @@ + +
text
+ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.php new file mode 100644 index 0000000..0069cf5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/SyntaxUnitTest.php @@ -0,0 +1,63 @@ + + * @author Blaine Schmeisser + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the Syntax sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\SyntaxSniff + */ +class SyntaxUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'SyntaxUnitTest.1.inc': + case 'SyntaxUnitTest.2.inc': + return [3 => 1]; + + default: + return []; + } + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc new file mode 100644 index 0000000..30c6d29 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc @@ -0,0 +1,98 @@ +null = 7; + +use Zend\Log\Writer\Null as NullWriter; +new \Zend\Log\Writer\Null(); + +namespace False; + +class True extends Null implements False {} + +use True\Something; +use Something\True; +class MyClass +{ + public function myFunction() + { + $var = array('foo' => new True()); + } +} + +$x = $f?false:TRUE; +$x = $f? false:TRUE; + +class MyClass +{ + // Spice things up a little. + const true = FALSE; +} + +var_dump(MyClass::true); + +function true() {} + +// Issue #3332 - ignore type declarations, but not default values. +class TypedThings { + const MYCONST = false; + + public int|false $int = false; + public Type|null $int = new MyObj(null); + + private function typed(int|false $param = null, Type|null $obj = new MyObj(false)) : string|false|null + { + if (true === false) { + return null; + } + } +} + +$cl = function (int|false $param = null, Type|null $obj = new MyObj(false)) : string|false|null {}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc.fixed new file mode 100644 index 0000000..7705198 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.inc.fixed @@ -0,0 +1,98 @@ +null = 7; + +use Zend\Log\Writer\Null as NullWriter; +new \Zend\Log\Writer\Null(); + +namespace False; + +class True extends Null implements False {} + +use True\Something; +use Something\True; +class MyClass +{ + public function myFunction() + { + $var = array('foo' => new True()); + } +} + +$x = $f?FALSE:TRUE; +$x = $f? FALSE:TRUE; + +class MyClass +{ + // Spice things up a little. + const true = FALSE; +} + +var_dump(MyClass::true); + +function true() {} + +// Issue #3332 - ignore type declarations, but not default values. +class TypedThings { + const MYCONST = FALSE; + + public int|false $int = FALSE; + public Type|null $int = new MyObj(NULL); + + private function typed(int|false $param = NULL, Type|null $obj = new MyObj(FALSE)) : string|false|null + { + if (TRUE === FALSE) { + return NULL; + } + } +} + +$cl = function (int|false $param = NULL, Type|null $obj = new MyObj(FALSE)) : string|false|null {}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.php new file mode 100644 index 0000000..dcfe801 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/PHP/UpperCaseConstantUnitTest.php @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the UpperCaseConstant sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\UpperCaseConstantSniff + */ +class UpperCaseConstantUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 10 => 1, + 15 => 1, + 16 => 1, + 23 => 1, + 26 => 1, + 31 => 1, + 32 => 1, + 39 => 1, + 42 => 1, + 47 => 1, + 48 => 1, + 70 => 1, + 71 => 1, + 85 => 1, + 87 => 1, + 88 => 1, + 90 => 2, + 92 => 2, + 93 => 1, + 98 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.inc new file mode 100644 index 0000000..43c05a1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.inc @@ -0,0 +1,21 @@ +'; +$code = '<'.'?php '; + +$string = 'This is a really long string. ' + . 'It is being used for errors. ' + . 'The message is not translated.'; +?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.js new file mode 100644 index 0000000..6be7900 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.js @@ -0,0 +1,15 @@ +var x = 'My ' + 'string'; +var x = 'My ' + 1234; +var x = 'My ' + y + ' test'; + +this.errors['test'] = x; +this.errors['test' + 10] = x; +this.errors['test' + y] = x; +this.errors['test' + 'blah'] = x; +this.errors[y] = x; +this.errors[y + z] = x; +this.errors[y + z + 'My' + 'String'] = x; + +var long = 'This is a really long string. ' + + 'It is being used for errors. ' + + 'The message is not translated.'; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.php new file mode 100644 index 0000000..ce08934 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/Strings/UnnecessaryStringConcatUnitTest.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\Strings; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the UnnecessaryStringConcat sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\Strings\UnnecessaryStringConcatSniff + */ +class UnnecessaryStringConcatUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'UnnecessaryStringConcatUnitTest.inc': + return [ + 2 => 1, + 6 => 1, + 9 => 1, + 12 => 1, + 19 => 1, + 20 => 1, + ]; + + case 'UnnecessaryStringConcatUnitTest.js': + return [ + 1 => 1, + 8 => 1, + 11 => 1, + 14 => 1, + 15 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.css b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.css new file mode 100644 index 0000000..de84a94 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.css @@ -0,0 +1,35 @@ +/* + * This is a CSS comment. +<<<<<<< HEAD + * This is a merge conflict... +======= + * which should be detected. +>>>>>>> ref/heads/feature-branch + */ + +.SettingsTabPaneWidgetType-tab-mid { + background: transparent url(tab_inact_mid.png) repeat-x; +<<<<<<< HEAD + line-height: -25px; +======= + line-height: -20px; +>>>>>>> ref/heads/feature-branch + cursor: pointer; + -moz-user-select: none; +} + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries, subsequent boundaries will still + * be detected correctly. + */ + +/* + * This is a CSS comment. +<<<<<<< HEAD + * This is a merge conflict... +======= + * which should be detected. +>>>>>>> ref/heads/feature-branch + */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.inc new file mode 100644 index 0000000..470c3b8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.1.inc @@ -0,0 +1,61 @@ +> -1); +var_dump( +1 +<< +-1 +); + +$string = +<< 'a' +<<<<<<< HEAD + 'b' => 'b' +======= + 'c' => 'c' +>>>>>>> master + ); + } + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries - i.e. after the first merge conflict + * opener in non-comment, non-heredoc/nowdoc, non-inline HTML code -, subsequent + * merge conflict boundaries will still be detected correctly. + */ + +/* + * Testing detecting subsequent merge conflicts. + * +<<<<<<< HEAD + * @var string $bar + */ +public function foo($bar){ } + +/** +============ +The above is not the boundary, the below is. +======= + * @var string $bar +>>>>>>> f19f8a5... Commit message +*/ + +// Test that stray boundaries, i.e. an opener without closer and such, are detected. +<<<<<<< HEAD +$a = 1; +======= diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.css b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.css new file mode 100644 index 0000000..6caa78d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.css @@ -0,0 +1,32 @@ +/* + * This is a CSS comment. +<<<<<<< HEAD + * This is a merge conflict started in a comment, ending in a CSS block. + */ +.SettingsTabPaneWidgetType-tab-mid { + background: transparent url(tab_inact_mid.png) repeat-x; +======= + * which should be detected. + **/ +.SettingsTabPaneWidgetType-tab-start { + line-height: -25px; +>>>>>>> ref/heads/feature-branch + cursor: pointer; + -moz-user-select: none; +} + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries, subsequent boundaries will still + * be detected correctly. + */ + +/* + * This is a CSS comment. +<<<<<<< HEAD + * This is a merge conflict... +======= + * which should be detected. +>>>>>>> ref/heads/feature-branch + */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.inc new file mode 100644 index 0000000..809b17d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.2.inc @@ -0,0 +1,31 @@ +>>>>>> master + */ + +/* + * Testing detecting merge conflicts using different comment styles. + * +<<<<<<< HEAD + * @var string $bar + */ +public function foo($bar){ } + +/* +======= + * @var string $bar +>>>>>>> master +*/ + +// Comment +<<<<<<< HEAD +// Second comment line. NOTE: The above opener breaks the tokenizer. +======= +// New second comment line +>>>>>>> master +// Third comment line diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.3.inc new file mode 100644 index 0000000..ce70941 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.3.inc @@ -0,0 +1,43 @@ + +
+<<<<<<< HEAD +

Testing a merge conflict.

+======= +

Another text string.

+>>>>>>> ref/heads/feature-branch +
+ + +
+<<<<<<< HEAD +

+======= +

+>>>>>>> ref/heads/feature-branch +
+ +>>>>>> master + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries - i.e. after the first merge conflict + * opener in non-comment, non-heredoc/nowdoc, non-inline HTML code -, subsequent + * merge conflict boundaries will still be detected correctly. + */ +?> + +
+<<<<<<< HEAD +

Testing a merge conflict.

+======= +

Another text string.

+>>>>>>> ref/heads/feature-branch +
diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.4.inc new file mode 100644 index 0000000..99c0b99 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.4.inc @@ -0,0 +1,71 @@ +>>>>>> ref/heads/other-branchname +And now they are. +EOD; + +// Heredoc with a merge conflict starter, the closer is outside the heredoc. +$string = +<<>>>>>> ref/heads/other-branchname + +// Merge conflict starter outside with a closer inside of the heredoc. +// This breaks the tokenizer. +<<<<<<< HEAD +$string = +<<>>>>>> ref/heads/other-branchname +EOD; + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries - i.e. after the first merge conflict + * opener in non-comment, non-heredoc/nowdoc, non-inline HTML code -, subsequent + * merge conflict boundaries will still be detected correctly. + */ + +$string = +<<>>>>>> ref/heads/other-branchname +And now they are. +EOD; + +$string = +<<>>>>>> ref/heads/other-branchname diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.5.inc new file mode 100644 index 0000000..7d55f6d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.5.inc @@ -0,0 +1,34 @@ +>>>>>> ref/heads/other-branchname +And now they are. +EOD; + +// Break the tokenizer. +<<<<<<< HEAD + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries - i.e. after the first merge conflict + * opener in non-comment, non-heredoc/nowdoc, non-inline HTML code -, subsequent + * merge conflict boundaries will still be detected correctly. + */ + +$string = +<<<'EOD' +can be problematic. +<<<<<<< HEAD +were previously not detected. +======= +should also be detected. +>>>>>>> ref/heads/other-branchname +And now they are. +EOD; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.6.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.6.inc new file mode 100644 index 0000000..aaea324 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.6.inc @@ -0,0 +1,34 @@ +>>>>>> ref/heads/other-branchname + And now they are. + EOD; + +// Break the tokenizer. +>>>>>>> master + +/* + * The above tests are based on "normal" tokens. + * The below test checks that once the tokenizer breaks down because of + * unexpected merge conflict boundaries - i.e. after the first merge conflict + * opener in non-comment, non-heredoc/nowdoc, non-inline HTML code -, subsequent + * merge conflict boundaries will still be detected correctly. + */ + +$string = + <<<"EOD" + Merge conflicts in PHP 7.3 indented heredocs +<<<<<<< HEAD + can be problematic. +======= + should also be detected. +>>>>>>> ref/heads/other-branchname + And now they are. + EOD; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.7.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.7.inc new file mode 100644 index 0000000..85cae1f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.7.inc @@ -0,0 +1,19 @@ + +
+<<<<<<< HEAD +

Testing a merge conflict.

+======= +

Another text string.

+>>>>>>> ref/heads/feature-branch +
+ + +
+<<<<<<< HEAD +

+======= +

+>>>>>>> ref/heads/feature-branch +
+ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.js new file mode 100644 index 0000000..cd7bc76 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.js @@ -0,0 +1,33 @@ + +result = x?y:z; +result = x ? y : z; + +<<<<<<< HEAD +if (something === true +======= +if (something === false +>>>>>>> develop + ^ somethingElse === true +) { +<<<<<<< HEAD + return true; +======= + return false; +>>>>>>> develop +} + +y = 1 + + 2 + - 3; + +/* +<<<<<<< HEAD + * @var string $bar + */ +if (something === true + +/** +======= + * @var string $foo +>>>>>>> master + */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.php new file mode 100644 index 0000000..f675182 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/GitMergeConflictUnitTest.php @@ -0,0 +1,175 @@ + + * @copyright 2017 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\VersionControl; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the GitMergeConflict sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\VersionControl\GitMergeConflictSniff + */ +class GitMergeConflictUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'GitMergeConflictUnitTest.1.inc': + return [ + 26 => 1, + 28 => 1, + 30 => 1, + 45 => 1, + 53 => 1, + 55 => 1, + 59 => 1, + 61 => 1, + ]; + + case 'GitMergeConflictUnitTest.2.inc': + return [ + 4 => 1, + 6 => 1, + 8 => 1, + 14 => 1, + 20 => 1, + 22 => 1, + 26 => 1, + 28 => 1, + 30 => 1, + ]; + + case 'GitMergeConflictUnitTest.3.inc': + return [ + 3 => 1, + 5 => 1, + 7 => 1, + 12 => 1, + 14 => 1, + 16 => 1, + 22 => 1, + 24 => 1, + 26 => 1, + 38 => 1, + 40 => 1, + 42 => 1, + ]; + + case 'GitMergeConflictUnitTest.4.inc': + return [ + 6 => 1, + 8 => 1, + 10 => 1, + 18 => 1, + 22 => 1, + 25 => 1, + 29 => 1, + 34 => 1, + 39 => 1, + 53 => 1, + 55 => 1, + 57 => 1, + 64 => 1, + 68 => 1, + 71 => 1, + ]; + case 'GitMergeConflictUnitTest.5.inc': + case 'GitMergeConflictUnitTest.6.inc': + return [ + 6 => 1, + 8 => 1, + 10 => 1, + 15 => 1, + 28 => 1, + 30 => 1, + 32 => 1, + ]; + + case 'GitMergeConflictUnitTest.7.inc': + return [ + 3 => 1, + 5 => 1, + 7 => 1, + 12 => 1, + 14 => 1, + 16 => 1, + ]; + + case 'GitMergeConflictUnitTest.1.css': + return [ + 3 => 1, + 5 => 1, + 7 => 1, + 12 => 1, + 14 => 1, + 16 => 1, + 30 => 1, + 32 => 1, + 34 => 1, + ]; + + case 'GitMergeConflictUnitTest.2.css': + return [ + 3 => 1, + 8 => 1, + 13 => 1, + 27 => 1, + 29 => 1, + 31 => 1, + ]; + + case 'GitMergeConflictUnitTest.js': + return [ + 5 => 1, + 7 => 1, + 9 => 1, + 12 => 1, + 14 => 1, + 16 => 1, + 24 => 1, + 30 => 1, + 32 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/SubversionPropertiesUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/SubversionPropertiesUnitTest.inc new file mode 100644 index 0000000..e4110de --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/VersionControl/SubversionPropertiesUnitTest.inc @@ -0,0 +1,3 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\VersionControl; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SubversionProperties sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\VersionControl\SubversionPropertiesSniff + */ +class SubversionPropertiesUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Should this test be skipped for some reason. + * + * @return bool + */ + protected function shouldSkipTest() + { + // This sniff cannot be tested as no SVN version control directory is available. + return true; + + }//end shouldSkipTest() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc new file mode 100644 index 0000000..8e17dbb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc @@ -0,0 +1,182 @@ +{$var}( $foo,$bar ); + +$bar(function( $a, $b ) { + return function( $c, $d ) use ( $a, $b ) { + echo $a, $b, $c, $d; + }; +})( 'a','b' )( 'c','d' ); + +$closure( $foo,$bar ); +$var = $closure() + $closure( $foo,$bar ) + self::$closure( $foo,$bar ); + +class Test { + public static function baz( $foo, $bar ) { + $a = new self( $foo,$bar ); + $b = new static( $foo,$bar ); + } +} + +/* + * Test warning for empty parentheses. + */ +$a = 4 + (); // Warning. +$a = 4 + ( ); // Warning. +$a = 4 + (/* Not empty */); + +/* + * Test the actual sniff. + */ +if ((null !== $extra) && ($row->extra !== $extra)) {} + +if (( null !== $extra ) && ( $row->extra !== $extra )) {} // Bad x 4. + +if (( null !== $extra // Bad x 1. + && is_int($extra)) + && ( $row->extra !== $extra // Bad x 1. + || $something ) // Bad x 1. +) {} + +if (( null !== $extra ) // Bad x 2. + && ( $row->extra !== $extra ) // Bad x 2. +) {} + +$a = (null !== $extra); +$a = ( null !== $extra ); // Bad x 2. + +$sx = $vert ? ($w - 1) : 0; + +$this->is_overloaded = ( ( ini_get("mbstring.func_overload") & 2 ) != 0 ) && function_exists('mb_substr'); // Bad x 4. + +$image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 ); + +if ( $success && ('nothumb' == $target || 'all' == $target) ) {} + +$directory = ('/' == $file[ strlen($file)-1 ]); + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 1 +if ((null !== $extra) && ($row->extra !== $extra)) {} // Bad x 4. + +if (( null !== $extra ) && ( $row->extra !== $extra )) {} + +if (( null !== $extra // Bad x 1. + && is_int($extra)) // Bad x 1. + && ( $row->extra !== $extra + || $something ) // Bad x 1. +) {} + +if ((null !== $extra) // Bad x 2. + && ($row->extra !== $extra) // Bad x 2. +) {} + +$a = (null !== $extra); // Bad x 2. +$a = ( null !== $extra ); + +$sx = $vert ? ($w - 1) : 0; // Bad x 2. + +$this->is_overloaded = ((ini_get("mbstring.func_overload") & 2) != 0) && function_exists('mb_substr'); // Bad x 4. + +$image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 ); // Bad x 4. + +if ( $success && ('nothumb' == $target || 'all' == $target) ) {} // Bad x 2. + +$directory = ('/' == $file[ strlen($file)-1 ]); // Bad x 2. + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 0 + +/* + * Test handling of ignoreNewlines. + */ +if ( + ( + null !== $extra + ) && ( + $row->extra !== $extra + ) +) {} // Bad x 4, 1 x line 123, 2 x line 125, 1 x line 127. + + +$a = ( + null !== $extra +); // Bad x 2, 1 x line 131, 1 x line 133. + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 1 +if ( + ( + null !== $extra + ) && ( + $row->extra !== $extra + ) +) {} // Bad x 4, 1 x line 137, 2 x line 139, 1 x line 141. + +$a = ( + null !== $extra +); // Bad x 2, 1 x line 144, 1 x line 146. +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 0 + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing ignoreNewlines true +if ( + ( + null !== $extra + ) && ( + $row->extra !== $extra + ) +) {} + +$a = ( + null !== $extra +); +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing ignoreNewlines false + +if (true) {} ( 1+2) === 3 ? $a = 1 : $a = 2; +class A {} ( 1+2) === 3 ? $a = 1 : $a = 2; +function foo() {} ( 1+2) === 3 ? $a = 1 : $a = 2; + +// Issue #3618. +class NonArbitraryParenthesesWithKeywords { + public static function baz( $foo, $bar ) { + $a = new self(); + $b = new parent(); + $c = new static(); + + // self/static are already tested above, round line 45. + $d = new parent( $foo,$bar ); + } +} + +// Test that the match expression does not trigger the sniff. +$b = match ( $a ) { + 1 => true, +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000..c215753 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.1.inc.fixed @@ -0,0 +1,170 @@ +{$var}( $foo,$bar ); + +$bar(function( $a, $b ) { + return function( $c, $d ) use ( $a, $b ) { + echo $a, $b, $c, $d; + }; +})( 'a','b' )( 'c','d' ); + +$closure( $foo,$bar ); +$var = $closure() + $closure( $foo,$bar ) + self::$closure( $foo,$bar ); + +class Test { + public static function baz( $foo, $bar ) { + $a = new self( $foo,$bar ); + $b = new static( $foo,$bar ); + } +} + +/* + * Test warning for empty parentheses. + */ +$a = 4 + (); // Warning. +$a = 4 + ( ); // Warning. +$a = 4 + (/* Not empty */); + +/* + * Test the actual sniff. + */ +if ((null !== $extra) && ($row->extra !== $extra)) {} + +if ((null !== $extra) && ($row->extra !== $extra)) {} // Bad x 4. + +if ((null !== $extra // Bad x 1. + && is_int($extra)) + && ($row->extra !== $extra // Bad x 1. + || $something) // Bad x 1. +) {} + +if ((null !== $extra) // Bad x 2. + && ($row->extra !== $extra) // Bad x 2. +) {} + +$a = (null !== $extra); +$a = (null !== $extra); // Bad x 2. + +$sx = $vert ? ($w - 1) : 0; + +$this->is_overloaded = ((ini_get("mbstring.func_overload") & 2) != 0) && function_exists('mb_substr'); // Bad x 4. + +$image->flip( ($operation->axis & 1) != 0, ($operation->axis & 2) != 0 ); + +if ( $success && ('nothumb' == $target || 'all' == $target) ) {} + +$directory = ('/' == $file[ strlen($file)-1 ]); + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 1 +if (( null !== $extra ) && ( $row->extra !== $extra )) {} // Bad x 4. + +if (( null !== $extra ) && ( $row->extra !== $extra )) {} + +if (( null !== $extra // Bad x 1. + && is_int($extra) ) // Bad x 1. + && ( $row->extra !== $extra + || $something ) // Bad x 1. +) {} + +if (( null !== $extra ) // Bad x 2. + && ( $row->extra !== $extra ) // Bad x 2. +) {} + +$a = ( null !== $extra ); // Bad x 2. +$a = ( null !== $extra ); + +$sx = $vert ? ( $w - 1 ) : 0; // Bad x 2. + +$this->is_overloaded = ( ( ini_get("mbstring.func_overload") & 2 ) != 0 ) && function_exists('mb_substr'); // Bad x 4. + +$image->flip( ( $operation->axis & 1 ) != 0, ( $operation->axis & 2 ) != 0 ); // Bad x 4. + +if ( $success && ( 'nothumb' == $target || 'all' == $target ) ) {} // Bad x 2. + +$directory = ( '/' == $file[ strlen($file)-1 ] ); // Bad x 2. + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 0 + +/* + * Test handling of ignoreNewlines. + */ +if ( + (null !== $extra) && ($row->extra !== $extra) +) {} // Bad x 4, 1 x line 123, 2 x line 125, 1 x line 127. + + +$a = (null !== $extra); // Bad x 2, 1 x line 131, 1 x line 133. + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 1 +if ( + ( null !== $extra ) && ( $row->extra !== $extra ) +) {} // Bad x 4, 1 x line 137, 2 x line 139, 1 x line 141. + +$a = ( null !== $extra ); // Bad x 2, 1 x line 144, 1 x line 146. +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing spacing 0 + +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing ignoreNewlines true +if ( + ( + null !== $extra + ) && ( + $row->extra !== $extra + ) +) {} + +$a = ( + null !== $extra +); +// phpcs:set Generic.WhiteSpace.ArbitraryParenthesesSpacing ignoreNewlines false + +if (true) {} (1+2) === 3 ? $a = 1 : $a = 2; +class A {} (1+2) === 3 ? $a = 1 : $a = 2; +function foo() {} (1+2) === 3 ? $a = 1 : $a = 2; + +// Issue #3618. +class NonArbitraryParenthesesWithKeywords { + public static function baz( $foo, $bar ) { + $a = new self(); + $b = new parent(); + $c = new static(); + + // self/static are already tested above, round line 45. + $d = new parent( $foo,$bar ); + } +} + +// Test that the match expression does not trigger the sniff. +$b = match ( $a ) { + 1 => true, +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.2.inc new file mode 100644 index 0000000..3d5bcd0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ArbitraryParenthesesSpacingUnitTest.2.inc @@ -0,0 +1,4 @@ + + * @copyright 2006-2017 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ArbitraryParenthesesSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ArbitraryParenthesesSpacingSniff + */ +class ArbitraryParenthesesSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ArbitraryParenthesesSpacingUnitTest.1.inc': + return [ + 64 => 4, + 66 => 1, + 68 => 1, + 69 => 1, + 72 => 2, + 73 => 2, + 77 => 2, + 81 => 4, + 90 => 4, + 94 => 1, + 95 => 1, + 97 => 1, + 100 => 2, + 101 => 2, + 104 => 2, + 107 => 2, + 109 => 4, + 111 => 4, + 113 => 2, + 115 => 2, + 123 => 1, + 125 => 2, + 127 => 1, + 131 => 1, + 133 => 1, + 137 => 1, + 139 => 2, + 141 => 1, + 144 => 1, + 146 => 1, + 163 => 1, + 164 => 1, + 165 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'ArbitraryParenthesesSpacingUnitTest.1.inc': + return [ + 55 => 1, + 56 => 1, + ]; + + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowSpaceIndentUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowSpaceIndentUnitTest.1.inc new file mode 100644 index 0000000..1826b58 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowSpaceIndentUnitTest.1.inc @@ -0,0 +1,118 @@ +"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// [space][space][space][tab]return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// Doc comments are indent with tabs and one space +//[tab]/** +//[tab][space]* + /** + * CVS revision for HTTP headers. + * + * @var string + * @access private + */ + /** + * + */ + +$str = 'hello + there'; + +/** + * This PHP DocBlock should be fine, even though there is a single space at the beginning. + * + * @var int $x + */ +$x = 1; + +?> + + + Foo + + +
+
+
+
+
+
+ + + +"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// [space][space][space][tab]return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// Doc comments are indent with tabs and one space +//[tab]/** +//[tab][space]* + /** + * CVS revision for HTTP headers. + * + * @var string + * @access private + */ + /** + * + */ + +$str = 'hello + there'; + +/** + * This PHP DocBlock should be fine, even though there is a single space at the beginning. + * + * @var int $x + */ +$x = 1; + +?> + + + Foo + + +
+
+
+
+
+
+ + + +"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// [space][space][space][tab]return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// Doc comments are indent with tabs and one space +//[tab]/** +//[tab][space]* + /** + * CVS revision for HTTP headers. + * + * @var string + * @access private + */ + /** + * + */ + +$str = 'hello + there'; + +/** + * This PHP DocBlock should be fine, even though there is a single space at the beginning. + * + * @var int $x + */ +$x = 1; + +?> + + + Foo + + +
+
+
+
+
+
+ + + +"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// [space][space][space][tab]return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; + return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; +// Doc comments are indent with tabs and one space +//[tab]/** +//[tab][space]* + /** + * CVS revision for HTTP headers. + * + * @var string + * @access private + */ + /** + * + */ + +$str = 'hello + there'; + +/** + * This PHP DocBlock should be fine, even though there is a single space at the beginning. + * + * @var int $x + */ +$x = 1; + +?> + + + Foo + + +
+
+
+
+
+
+ + + + + + + Foo + + +
+
+
+
+
+
+ + + + + + + Foo + + +
+
+
+
+
+
+ + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowSpaceIndent sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\DisallowSpaceIndentSniff + */ +class DisallowSpaceIndentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + if ($testFile === 'DisallowSpaceIndentUnitTest.2.inc') { + return; + } + + $config->tabWidth = 4; + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowSpaceIndentUnitTest.1.inc': + case 'DisallowSpaceIndentUnitTest.2.inc': + return [ + 5 => 1, + 9 => 1, + 15 => 1, + 22 => 1, + 24 => 1, + 30 => 1, + 35 => 1, + 50 => 1, + 55 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 60 => 1, + 65 => 1, + 66 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 73 => 1, + 77 => 1, + 81 => 1, + 104 => 1, + 105 => 1, + 106 => 1, + 107 => 1, + 108 => 1, + 110 => 1, + 111 => 1, + 112 => 1, + 114 => 1, + 115 => 1, + 117 => 1, + 118 => 1, + ]; + + case 'DisallowSpaceIndentUnitTest.3.inc': + return [ + 2 => 1, + 5 => 1, + 10 => 1, + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + ]; + + case 'DisallowSpaceIndentUnitTest.js': + return [3 => 1]; + + case 'DisallowSpaceIndentUnitTest.css': + return [2 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowTabIndentUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowTabIndentUnitTest.1.inc new file mode 100644 index 0000000..cf61177 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/DisallowTabIndentUnitTest.1.inc @@ -0,0 +1,93 @@ + 'Czech republic', + 'România' => 'Romania', + 'Magyarország' => 'Hungary', +); + +$var = "$hello $there"; + +?> + + + Foo + + +
+
+
+
+
+
+ + + + 'Czech republic', + 'România' => 'Romania', + 'Magyarország' => 'Hungary', +); + +$var = "$hello $there"; + +?> + + + Foo + + +
+
+
+
+
+
+ + + + + + + Foo + + +
+
+
+
+
+
+ + + + + + + Foo + + +
+
+
+
+
+
+ + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowTabIndent sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\DisallowTabIndentSniff + */ +class DisallowTabIndentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + $config->tabWidth = 4; + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowTabIndentUnitTest.1.inc': + return [ + 5 => 2, + 9 => 1, + 15 => 1, + 20 => 2, + 21 => 1, + 22 => 2, + 23 => 1, + 24 => 2, + 31 => 1, + 32 => 2, + 33 => 2, + 41 => 1, + 42 => 1, + 43 => 1, + 44 => 1, + 45 => 1, + 46 => 1, + 47 => 1, + 48 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + 82 => 1, + 83 => 1, + 85 => 1, + 86 => 1, + 87 => 1, + 89 => 1, + 90 => 1, + 92 => 1, + 93 => 1, + ]; + + case 'DisallowTabIndentUnitTest.2.inc': + return [ + 6 => 1, + 7 => 1, + 8 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 19 => 1, + ]; + + case 'DisallowTabIndentUnitTest.3.inc': + if (\PHP_VERSION_ID >= 70300) { + return [ + 7 => 1, + 13 => 1, + ]; + } + + // PHP 7.2 or lower: PHP version which doesn't support flexible heredocs/nowdocs yet. + return []; + + case 'DisallowTabIndentUnitTest.js': + return [ + 3 => 1, + 5 => 1, + 6 => 1, + ]; + + case 'DisallowTabIndentUnitTest.css': + return [ + 1 => 1, + 2 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc new file mode 100644 index 0000000..b674466 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc @@ -0,0 +1,37 @@ +prop++; +$obj->prop ++; +$obj?->prop ++; + +$obj->obj->prop++; +$obj->obj->prop ++; +$obj?->obj->prop ++; + +$obj->prop['key']++; +$obj->prop['key'] ++; + +--ClassName::$prop; +-- ClassName::$prop; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..1049e7e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.inc.fixed @@ -0,0 +1,36 @@ +prop++; +$obj->prop++; +$obj?->prop++; + +$obj->obj->prop++; +$obj->obj->prop++; +$obj?->obj->prop++; + +$obj->prop['key']++; +$obj->prop['key']++; + +--ClassName::$prop; +--ClassName::$prop; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js new file mode 100644 index 0000000..b7b1c2f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js @@ -0,0 +1,17 @@ +var i; + +i = 10; +--i; +-- i; +-- /*comment*/ i; +++i; +++ + i; +++/*comment*/i; + +i--; +i --; +i /*comment*/ --; +i++; +i ++; +i /*comment*/ ++; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js.fixed new file mode 100644 index 0000000..5d8b33a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.js.fixed @@ -0,0 +1,16 @@ +var i; + +i = 10; +--i; +--i; +-- /*comment*/ i; +++i; +++i; +++/*comment*/i; + +i--; +i--; +i /*comment*/ --; +i++; +i++; +i /*comment*/ ++; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.php new file mode 100644 index 0000000..ce6e114 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/IncrementDecrementSpacingUnitTest.php @@ -0,0 +1,84 @@ + + * @copyright 2018 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the IncrementDecrementSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\IncrementDecrementSpacingSniff + */ +class IncrementDecrementSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + $errors = [ + 5 => 1, + 6 => 1, + 8 => 1, + 10 => 1, + 13 => 1, + 14 => 1, + 16 => 1, + 17 => 1, + ]; + + switch ($testFile) { + case 'IncrementDecrementSpacingUnitTest.inc': + $errors[21] = 1; + $errors[23] = 1; + $errors[26] = 1; + $errors[27] = 1; + $errors[30] = 1; + $errors[31] = 1; + $errors[34] = 1; + $errors[37] = 1; + + return $errors; + + case 'IncrementDecrementSpacingUnitTest.js': + return $errors; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.1.inc new file mode 100644 index 0000000..1847778 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.1.inc @@ -0,0 +1,91 @@ + + * @copyright 2006-2017 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LanguageConstructSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\LanguageConstructSpacingSniff + */ +class LanguageConstructSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'LanguageConstructSpacingUnitTest.1.inc': + return [ + 3 => 1, + 5 => 1, + 8 => 1, + 10 => 1, + 13 => 1, + 15 => 1, + 18 => 1, + 20 => 1, + 23 => 1, + 25 => 1, + 28 => 1, + 30 => 1, + 33 => 1, + 36 => 1, + 39 => 1, + 40 => 1, + 43 => 1, + 44 => 1, + 45 => 1, + 46 => 1, + 48 => 1, + 52 => 1, + 55 => 1, + 56 => 1, + 57 => 2, + 60 => 1, + 63 => 1, + 65 => 1, + 73 => 1, + 75 => 1, + 77 => 1, + 81 => 1, + 83 => 1, + 85 => 1, + 86 => 1, + 90 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc new file mode 100644 index 0000000..4061aff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc @@ -0,0 +1,1618 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false + +hello(); + } + + function hello() + { + echo 'hello'; +}//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+    $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): +if ($bar) $foo = 1; +elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { +if (false) { +echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( +'some long description', function () { + }); +} + +switch ( $a ) { +case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'b': + $b = 3; +?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, +false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => +$value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed new file mode 100644 index 0000000..7b5efea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.inc.fixed @@ -0,0 +1,1618 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false + +hello(); + } + + function hello() + { + echo 'hello'; + }//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+    $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): + if ($bar) $foo = 1; + elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { + if (false) { + echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( + 'some long description', function () { + }); +} + +switch ( $a ) { + case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'b': + $b = 3; + ?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => + $value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js new file mode 100644 index 0000000..2195bfb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js @@ -0,0 +1,239 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false +var script = document.createElement('script'); +script.onload = function() +{ + clearTimeout(t); + script456.onload = null; + script.onreadystatechange = null; + callback.call(this); + +}; + +this.callbacks[type] = { + namespaces: {}, +others: [] +}; + +blah = function() +{ + print something; + + } + +test(blah, function() { + print something; +}); + +var test = [{x: 10}]; +var test = [{ + x: 10, + y: { + b14h: 12, + 'b14h': 12 + }, + z: 23 +}]; + +Viper.prototype = { + + _removeEvents: function(elem) + { + if (!elem) { + elem = this.element; + } + + ViperUtil.removeEvent(elem, '.' + this.getEventNamespace()); + + } + +}; + +this.init = function(data) { + if (_pageListWdgt) { + GUI.getWidget('changedPagesList').addItemClickedCallback( + function(itemid, target) { + draftChangeTypeClicked( + itemid, + target, + { + reviewData: _reviewData, + pageid: itemid + } + ); + } + ); + }//end if + +}; + +a( + function() { + var _a = function() { + b = false; + + }; + true + } +); + +(function() { + a = function() { + a(function() { + if (true) { + a = true; + } + }); + + a( + function() { + if (true) { + if (true) { + a = true; + } + } + } + ); + + a( + function() { + if (true) { + a = true; + } + } + ); + + }; + +})(); + +a.prototype = { + + a: function() + { + var currentSize = null; + ViperUtil.addEvent( + header, + 'safedblclick', + function() {}, + ); + + if (topContent) { + ViperUtil.addClass(topContent, 'Viper-popup-top'); + main.appendChild(topContent); + } + + ViperUtil.addClass(midContent, 'Viper-popup-content'); + main.appendChild(midContent); + } + +}; + +a.prototype = { + + a: function() + { + ViperUtil.addClass(midContent, 'Viper-popup-content'); + main.appendChild(midContent); + + var mouseUpAction = function() {}; + var preventMouseUp = false; + var self = this; + if (clickAction) { + } + } + +}; + +a.prototype = { + + a: function() + { + var a = function() { + var a = 'foo'; + }; + + if (true) { + } + + }, + + b: function() + { + ViperUtil.addEvent( + function() { + if (fullScreen !== true) { + currentSize = { + }; + + showfullScreen(); + } + } + ); + + }, + + c: function() + { + this.a( + { + a: function() { + form.onsubmit = function() { + return false; + }; + + var a = true; + } + } + ); + + } + +}; + +a.prototype = { + init: function() + {}, + + _b: function() + { + } + +}; + +for (var i = 0; i < 10; i++) { + var foo = {foo:{'a':'b', + 'c':'d'}}; +} + +class TestOk +{ + destroy() + { + setTimeout(a, 1000); + + if (typeof self.callbackOnClose === "function") { + self.callbackOnClose(); + } + } +} + +class TestBad +{ + destroy() + { + setTimeout(function () { + return; + }, 1000); + + if (typeof self.callbackOnClose === "function") { + self.callbackOnClose(); + } + } +} + +( function( $ ) { + foo(function( value ) { + value.bind( function( newval ) { + $( '#bar' ).html( newval ); + } ); + } )( jQuery ); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js.fixed new file mode 100644 index 0000000..d4bf409 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.1.js.fixed @@ -0,0 +1,239 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false +var script = document.createElement('script'); +script.onload = function() +{ + clearTimeout(t); + script456.onload = null; + script.onreadystatechange = null; + callback.call(this); + +}; + +this.callbacks[type] = { + namespaces: {}, + others: [] +}; + +blah = function() +{ + print something; + +} + +test(blah, function() { + print something; +}); + +var test = [{x: 10}]; +var test = [{ + x: 10, + y: { + b14h: 12, + 'b14h': 12 + }, + z: 23 +}]; + +Viper.prototype = { + + _removeEvents: function(elem) + { + if (!elem) { + elem = this.element; + } + + ViperUtil.removeEvent(elem, '.' + this.getEventNamespace()); + + } + +}; + +this.init = function(data) { + if (_pageListWdgt) { + GUI.getWidget('changedPagesList').addItemClickedCallback( + function(itemid, target) { + draftChangeTypeClicked( + itemid, + target, + { + reviewData: _reviewData, + pageid: itemid + } + ); + } + ); + }//end if + +}; + +a( + function() { + var _a = function() { + b = false; + + }; + true + } +); + +(function() { + a = function() { + a(function() { + if (true) { + a = true; + } + }); + + a( + function() { + if (true) { + if (true) { + a = true; + } + } + } + ); + + a( + function() { + if (true) { + a = true; + } + } + ); + + }; + +})(); + +a.prototype = { + + a: function() + { + var currentSize = null; + ViperUtil.addEvent( + header, + 'safedblclick', + function() {}, + ); + + if (topContent) { + ViperUtil.addClass(topContent, 'Viper-popup-top'); + main.appendChild(topContent); + } + + ViperUtil.addClass(midContent, 'Viper-popup-content'); + main.appendChild(midContent); + } + +}; + +a.prototype = { + + a: function() + { + ViperUtil.addClass(midContent, 'Viper-popup-content'); + main.appendChild(midContent); + + var mouseUpAction = function() {}; + var preventMouseUp = false; + var self = this; + if (clickAction) { + } + } + +}; + +a.prototype = { + + a: function() + { + var a = function() { + var a = 'foo'; + }; + + if (true) { + } + + }, + + b: function() + { + ViperUtil.addEvent( + function() { + if (fullScreen !== true) { + currentSize = { + }; + + showfullScreen(); + } + } + ); + + }, + + c: function() + { + this.a( + { + a: function() { + form.onsubmit = function() { + return false; + }; + + var a = true; + } + } + ); + + } + +}; + +a.prototype = { + init: function() + {}, + + _b: function() + { + } + +}; + +for (var i = 0; i < 10; i++) { + var foo = {foo:{'a':'b', + 'c':'d'}}; +} + +class TestOk +{ + destroy() + { + setTimeout(a, 1000); + + if (typeof self.callbackOnClose === "function") { + self.callbackOnClose(); + } + } +} + +class TestBad +{ + destroy() + { + setTimeout(function () { + return; + }, 1000); + + if (typeof self.callbackOnClose === "function") { + self.callbackOnClose(); + } + } +} + +( function( $ ) { + foo(function( value ) { + value.bind( function( newval ) { + $( '#bar' ).html( newval ); + } ); + } )( jQuery ); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc new file mode 100644 index 0000000..e725314 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc @@ -0,0 +1,1618 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent true + +hello(); + } + + function hello() + { + echo 'hello'; +}//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+	$safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): +if ($bar) $foo = 1; +elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { +if (false) { +echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( +'some long description', function () { + }); +} + +switch ( $a ) { +case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + +case 'b': + $b = 3; +?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, +false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => +$value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed new file mode 100644 index 0000000..57caa29 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.2.inc.fixed @@ -0,0 +1,1618 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent true + +hello(); + } + + function hello() + { + echo 'hello'; + }//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+	$safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* This is a T_COMMENT + * + * + * + */ + + /** This is a T_DOC_COMMENT + */ + + /* + This T_COMMENT has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + + + + doSomething( + function () { + echo 123; + } + ); + } +} + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +some_function( + function() { + $a = 403; + if ($a === 404) { + $a = 403; + } + } +); + +$myFunction = function() { + $a = 403; + if ($a === 404) { + $a = 403; + } +}; + +class Whatever +{ + protected $_protectedArray = array( + 'normalString' => 'That email address is already in use!', + 'offendingString' => <<<'STRING' +Each line of this string is always said to be at column 0, + no matter how many spaces are placed + at the beginning of each line +and the ending STRING on the next line is reported as having to be indented. +STRING + ); +} + +class MyClass +{ + public static function myFunction() + { + if (empty($keywords) === FALSE) { + $keywords = 'foo'; + $existing = 'foo'; + } + + return $keywords; + + }//end myFunction() + +}//end class + +$var = call_user_func( + $new_var = function () use (&$a) { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + } +); + +class AnonymousFn +{ + public function getAnonFn() + { + return array( + 'functions' => Array( + 'function1' => function ($a, $b, $c) { + $a = $b + $c; + $b = $c / 2; + return Array($a, $b, $c); + }, + ), + ); + } +} +?> + +
+ +
+
+ +
+
+ +
+ + "") { + $test = true; + } else { + $test = true; + } + } + ?> + + + +
+
+
+ +
+
+
+ + +

some text

+ function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } +]; + +if ($foo) { + foreach ($bar as $baz) { + if ($baz) { + ?> +
+
+
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ 1) { + echo '1'; + } + ?> +
+ +<?= CHtml::encode($this->pageTitle); ?> + +expects($this->at(2)) + ->with($this->callback( + function ($subject) + { + } + ) + ); + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +echo $string->append('foo') + ->appaend('bar') + ->appaend('baz') + ->outputUsing( + function () + { + } + ); + +echo PHP_EOL; + +switch ($arg) { + case 1: + break; + case 2: + if ($arg2 == 'foo') { + } + case 3: + default: + echo 'default'; +} + +if ($tokens[$stackPtr]['content']{0} === '#') { +} else if ($tokens[$stackPtr]['content']{0} === '/' + && $tokens[$stackPtr]['content']{1} === '/' +) { +} + +$var = call_user_func( + function() { + if ($foo) { + $new_var = function() { + if ($a > 0) { + return $a++; + } else { + return $a--; + } + }; + } + } +); + +a( + function() { + $a = function() { + $b = false; + }; + true; + } +); + +$var = [ + [ + '1' => + function () { + return true; + }, + ], + [ + '1' => + function () { + return true; + }, + '2' => true, + ] +]; + +if ($foo) { + ?> +

+ self::_replaceKeywords($failingComment, $result), + 'screenshot' => Test::getScreenshotPath( + $projectid, + $result['class_name'], + ), + ); + +} + +$this->mockedDatabase + ->with( + $this->callback( + function () { + return; + } + ) + ); + +$this->subject->recordLogin(); + +function a() +{ + if (true) { + static::$a[$b] = + static::where($c) + ->where($c) + ->where( + function ($d) { + $d->whereNull(); + $d->orWhere(); + } + ) + ->first(); + + if (static::$a[$b] === null) { + static::$a[$b] = new static( + array( + 'a' => $a->id, + 'a' => $a->id, + ) + ); + } + } + + return static::$a[$b]; +} + +$foo->load( + array( + 'bar' => function ($baz) { + $baz->call(); + } + ) +); + +hello(); + +$foo = array_unique( + array_map( + function ($entry) { + return $entry * 2; + }, + array() + ) +); +bar($foo); + +class PHP_CodeSniffer_Tokenizers_JS +{ + + public $scopeOpeners = array( + T_CASE => array( + 'end' => array( + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + ), + 'strict' => true, + ), + ); +} + +echo $string-> + append('foo')-> + appaend('bar')-> + appaend('baz')-> + outputUsing( + function () + { + } + ); + +$str = 'the items I want to show are: ' . + implode( + ', ', + array('a', 'b', 'c') + ); + +echo $str; + +$str = 'foo' + . '1' + . '2'; + +echo $str; + +bar([ + 'foo' => foo(function () { + return 'foo'; + }) +]); + +$domains = array_unique( + array_map( + function ($url) { + $urlObject = new \Purl\Url($url); + return $urlObject->registerableDomain; + }, + $sites + ) +); + +return $domains; + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +if ($foo): + if ($bar) $foo = 1; + elseif ($baz) $foo = 2; +endif; + +$this + ->method(array( + 'foo' => 'bar', + ), 'arg', array( + 'foo' => 'bar', + )); + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +class Foo +{ + use Bar { + myMethod as renamedMethod; + } +} + +foo(); + +array( + 'key1' => function ($bar) { + return $bar; + }, + 'key2' => function ($foo) { + return $foo; + }, +); + +?> + + 1, + ]; +$c = 2; + +class foo +{ + public function get() + { + $foo = ['b' => 'c', + 'd' => [ + ['e' => 'f'] + ]]; + echo '42'; + + $foo = array('b' => 'c', + 'd' => array( + array('e' => 'f') + )); + echo '42'; + } +} + +switch ($foo) { + case 1: + return array(); + case 2: + return ''; + case 3: + return $function(); + case 4: + return $functionCall($param[0]); + case 5: + return array() + array(); // Array Merge + case 6: + // String connect + return $functionReturningString('') . $functionReturningString(array()); + case 7: + return functionCall( + $withMultiLineParam[0], + array(), + $functionReturningString( + $withMultiLineParam[1] + ) + ); + case 8: + return $param[0][0]; +} + +class Test { + + public + $foo + ,$bar + ,$baz = [ ] + ; + + public function wtfindent() { + } +} + +switch ($x) { + case 1: + return [1]; + default: + return [2]; +} + +switch ($foo) { + case self::FOO: + return $this->bar($gfoo, function ($id) { + return FOO::bar($id); + }, $values); + case self::BAR: + $values = $this->bar($foo, $values); + break; +} + +$var = array( + 'long description' => + array(0, 'something'), + 'another long description' => + array(1, "something else") +); + +$services = array( + 'service 1' => + Mockery::mock('class 1') + ->shouldReceive('setFilter')->once() + ->shouldReceive('getNbResults')->atLeast()->once() + ->shouldReceive('getSlice')->once()->andReturn(array()) + ->getMock(), + 'service 2' => + Mockery::mock('class 2') + ->shouldReceive('__invoke')->once() + ->getMock() +); + +class Foo +{ + public function setUp() + { + $this->foo = new class { + public $name = 'Some value'; + }; + } +} + +try { + foo(); +} catch (\Exception $e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +if ($foo) { + foo(); +} else if ($e) { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} else { + $foo = function() { + return 'foo'; + }; + + if (true) { + } +} + +switch ($parameter) { + case null: + return [ + 'foo' => in_array( + 'foo', + [] + ), + ]; + + default: + return []; +} + +class SomeClass +{ + public function someFunc() + { + a(function () { + echo "a"; + })->b(function () { + echo "b"; + }); + + if (true) { + echo "c"; + } + echo "d"; + } +} + +$params = self::validate_parameters(self::read_competency_framework_parameters(), + array( + 'id' => $id, + )); + +$framework = api::read_framework($params['id']); +self::validate_context($framework->get_context()); +$output = $PAGE->get_renderer('tool_lp'); + +class Test123 +{ + protected static + $prop1 = [ + 'testA' => 123, + ], + $prop2 = [ + 'testB' => 456, + ]; + + protected static + $prop3 = array( + 'testA' => 123, + ), + $prop4 = array( + 'testB' => 456, + ); + + protected static $prop5; +} + +$foo = foo( + function () { + $foo->debug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +if (somethingIsTrue()) { + ?> +
+ +
+ bar(foo(function () { + }), foo(function () { + })); + +echo 'foo'; + +class Test { + + public function a() { + ?>adebug( + $a, + $b + ); + + if ($a) { + $b = $a; + } + } +); + +function test() +{ + $array = []; + foreach ($array as $data) { + [ + 'key1' => $var1, + 'key2' => $var2, + ] = $data; + foreach ($var1 as $method) { + echo $method . $var2; + } + } +} + +switch ($a) { + case 0: + $a = function () { + }; + case 1: + break; +} + +class Test +{ + public function __construct() + { + if (false) { + echo 0; + } + } +} + +return [ + 'veryLongKeySoIWantToMakeALineBreak' + => 'veryLonValueSoIWantToMakeALineBreak', + + 'someOtherKey' => [ + 'someValue' + ], + + 'arrayWithArraysInThere' => [ + ['Value1', 'Value1'] + ], +]; + +switch ($sContext) { + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +array_map( + static function ( $item ) { + echo $item; + }, + $some_array +); + +/** + * Comment. + */ +$a(function () use ($app) { + echo 'hi'; +})(); + +$app->run(); + +function foo() +{ + $foo('some + long description', function () { + }); + + $foo('some + long + description', function () { + }); + + $foo( + 'some long description', function () { + }); +} + +switch ( $a ) { + case 'a': + $b = 2; + /** + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'aa': + $b = 2; + /* + * A comment. + */ + apply_filter( 'something', $b ); + break; + + case 'b': + $b = 3; + ?> + + + + + +
+ +
+ +
+ +
+ + +
+ + + +
+ [ + ], + 'b' => <<<'FOO' +foo; +FOO + ], + $a, +]; + +$query = Model::query() + ->when($a, function () { + static $b = ''; + }); + +$result = array_map( + static fn(int $number) : int => $number + 1, + $numbers +); + +$a = $a === true ? [ + 'a' => 1, + ] : [ + 'a' => 100, +]; + +return [ + Url::make('View Song', fn($song) => $song->url()) + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +echo $string?->append('foo') + ?->outputUsing(); + +// phpcs:set Generic.WhiteSpace.ScopeIndent exact true +echo $string?->append('foo') + ?->outputUsing(); +// phpcs:set Generic.WhiteSpace.ScopeIndent exact false + +if (true) { + ?> null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ($value) { + '' => null, + false => false, + 1, 2, 3 => true, + default => $value, +}; + +$value = match ( + $value + ) { + '' => null, + false + => false, + 1, + 2, + 3 => true, + default => + $value, +}; + +function toString(): string +{ + return sprintf( + '%s', + match ($type) { + 'foo' => 'bar', + }, + ); +} + +$list = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + }, + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + $list2 = [ + 'fn' => function ($a) { + if ($a === true) { + echo 'hi'; + } + } + ]; + } + } +]; + +$foo = match ($type) { + 'a' => [ + 'aa' => 'DESC', + 'ab' => 'DESC', + ], + 'b' => [ + 'ba' => 'DESC', + 'bb' => 'DESC', + ], + default => [ + 'da' => 'DESC', + ], +}; + +$a = [ + 'a' => [ + 'a' => fn () => foo() + ], + 'a' => [ + 'a' => 'a', + ] +]; + +switch ($foo) { + case 'a': + $foo = match ($foo) { + 'bar' => 'custom_1', + default => 'a' + }; + return $foo; + case 'b': + return match ($foo) { + 'bar' => 'custom_1', + default => 'b' + }; + default: + return 'default'; +} + +foo(function ($foo) { + return [ + match ($foo) { + } + ]; +}); + +/* ADD NEW TESTS ABOVE THIS LINE AND MAKE SURE THAT THE 1 (space-based) AND 2 (tab-based) FILES ARE IN SYNC! */ +?> + + + + + + + <<<'INTRO' + lorem ipsum + INTRO, + 'em' => [ + [ + '', + ], + ], + 'abc' => [ + 'a' => 'wop wop', + 'b' => 'ola ola.', + ], +]; + +echo "" diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc new file mode 100644 index 0000000..55d1a06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc @@ -0,0 +1,28 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false +phpcs:set Generic.WhiteSpace.ScopeIndent exact true + $enabled, + 'compression' => $compression, + ] = $options; +} + +$this->foo() + ->bar() + ->baz(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc.fixed new file mode 100644 index 0000000..e9ae5ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.3.inc.fixed @@ -0,0 +1,28 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false +phpcs:set Generic.WhiteSpace.ScopeIndent exact true + $enabled, + 'compression' => $compression, + ] = $options; +} + +$this->foo() + ->bar() + ->baz(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.4.inc new file mode 100644 index 0000000..e58dc4d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/ScopeIndentUnitTest.4.inc @@ -0,0 +1,6 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ScopeIndent sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff + */ +class ScopeIndentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + // Tab width setting is only needed for the tabbed file. + if ($testFile === 'ScopeIndentUnitTest.2.inc') { + $config->tabWidth = 4; + } else { + $config->tabWidth = 0; + } + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile === 'ScopeIndentUnitTest.1.js') { + return [ + 6 => 1, + 14 => 1, + 21 => 1, + 30 => 1, + 32 => 1, + 33 => 1, + 34 => 1, + 39 => 1, + 42 => 1, + 59 => 1, + 60 => 1, + 75 => 1, + 120 => 1, + 121 => 1, + 122 => 1, + 123 => 1, + 141 => 1, + 142 => 1, + 155 => 1, + 156 => 1, + 168 => 1, + 184 => 1, + ]; + }//end if + + if ($testFile === 'ScopeIndentUnitTest.3.inc') { + return [ + 6 => 1, + 7 => 1, + 10 => 1, + ]; + } + + if ($testFile === 'ScopeIndentUnitTest.4.inc') { + return []; + } + + return [ + 7 => 1, + 10 => 1, + 13 => 1, + 17 => 1, + 20 => 1, + 24 => 1, + 25 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 58 => 1, + 123 => 1, + 224 => 1, + 225 => 1, + 279 => 1, + 280 => 1, + 281 => 1, + 282 => 1, + 283 => 1, + 284 => 1, + 285 => 1, + 286 => 1, + 336 => 1, + 349 => 1, + 380 => 1, + 386 => 1, + 387 => 1, + 388 => 1, + 389 => 1, + 390 => 1, + 397 => 1, + 419 => 1, + 420 => 1, + 465 => 1, + 467 => 1, + 472 => 1, + 473 => 1, + 474 => 1, + 496 => 1, + 498 => 1, + 500 => 1, + 524 => 1, + 526 => 1, + 544 => 1, + 545 => 1, + 546 => 1, + 639 => 1, + 660 => 1, + 662 => 1, + 802 => 1, + 803 => 1, + 823 => 1, + 858 => 1, + 879 => 1, + 1163 => 1, + 1197 => 1, + 1198 => 1, + 1259 => 1, + 1264 => 1, + 1265 => 1, + 1266 => 1, + 1269 => 1, + 1272 => 1, + 1273 => 1, + 1274 => 1, + 1275 => 1, + 1276 => 1, + 1277 => 1, + 1280 => 1, + 1281 => 1, + 1282 => 1, + 1284 => 1, + 1285 => 1, + 1288 => 1, + 1289 => 1, + 1290 => 1, + 1292 => 1, + 1293 => 1, + 1310 => 1, + 1312 => 1, + 1327 => 1, + 1328 => 1, + 1329 => 1, + 1330 => 1, + 1331 => 1, + 1332 => 1, + 1335 => 1, + 1340 => 1, + 1342 => 1, + 1345 => 1, + 1488 => 1, + 1489 => 1, + 1500 => 1, + 1503 => 1, + 1518 => 1, + 1520 => 1, + 1527 => 1, + 1529 => 1, + 1530 => 1, + 1590 => 1, + 1591 => 1, + 1592 => 1, + 1593 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/SpreadOperatorSpacingAfterUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/SpreadOperatorSpacingAfterUnitTest.inc new file mode 100644 index 0000000..fb5c181 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests/WhiteSpace/SpreadOperatorSpacingAfterUnitTest.inc @@ -0,0 +1,79 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Generic\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SpreadOperatorSpacingAfter sniff. + * + * @covers \PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\SpreadOperatorSpacingAfterSniff + */ +class SpreadOperatorSpacingAfterUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 12 => 1, + 13 => 1, + 20 => 2, + 40 => 1, + 41 => 1, + 46 => 2, + 60 => 1, + 61 => 1, + 66 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/ruleset.xml new file mode 100644 index 0000000..728426e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/ruleset.xml @@ -0,0 +1,4 @@ + + + A collection of generic sniffs. This standard is not designed to be used to check code. + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/CSS/BrowserSpecificStylesSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/CSS/BrowserSpecificStylesSniff.php new file mode 100644 index 0000000..9d02672 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/CSS/BrowserSpecificStylesSniff.php @@ -0,0 +1,87 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\CSS; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class BrowserSpecificStylesSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + /** + * A list of specific stylesheet suffixes we allow. + * + * These stylesheets contain browser specific styles + * so this sniff ignore them files in the form: + * *_moz.css and *_ie7.css etc. + * + * @var array + */ + protected $specificStylesheets = [ + 'moz' => true, + 'ie' => true, + 'ie7' => true, + 'ie8' => true, + 'webkit' => true, + ]; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // Ignore files with browser-specific suffixes. + $filename = $phpcsFile->getFilename(); + $breakChar = strrpos($filename, '_'); + if ($breakChar !== false && substr($filename, -4) === '.css') { + $specific = substr($filename, ($breakChar + 1), -4); + if (isset($this->specificStylesheets[$specific]) === true) { + return; + } + } + + $tokens = $phpcsFile->getTokens(); + $content = $tokens[$stackPtr]['content']; + + if ($content[0] === '-') { + $error = 'Browser-specific styles are not allowed'; + $phpcsFile->addError($error, $stackPtr, 'ForbiddenStyle'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/DisallowSelfActionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/DisallowSelfActionsSniff.php new file mode 100644 index 0000000..241104d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/DisallowSelfActionsSniff.php @@ -0,0 +1,125 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Channels; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class DisallowSelfActionsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLASS]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // We are not interested in abstract classes. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($prev !== false && $tokens[$prev]['code'] === T_ABSTRACT) { + return; + } + + // We are only interested in Action classes. + $classNameToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $className = $tokens[$classNameToken]['content']; + if (substr($className, -7) !== 'Actions') { + return; + } + + $foundFunctions = []; + $foundCalls = []; + + // Find all static method calls in the form self::method() in the class. + $classEnd = $tokens[$stackPtr]['scope_closer']; + for ($i = ($classNameToken + 1); $i < $classEnd; $i++) { + if ($tokens[$i]['code'] !== T_DOUBLE_COLON) { + if ($tokens[$i]['code'] === T_FUNCTION) { + // Cache the function information. + $funcName = $phpcsFile->findNext(T_STRING, ($i + 1)); + $funcScope = $phpcsFile->findPrevious(Tokens::$scopeModifiers, ($i - 1)); + + $foundFunctions[$tokens[$funcName]['content']] = strtolower($tokens[$funcScope]['content']); + } + + continue; + } + + $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), null, true); + if ($tokens[$prevToken]['content'] !== 'self' + && $tokens[$prevToken]['content'] !== 'static' + ) { + continue; + } + + $funcNameToken = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true); + if ($tokens[$funcNameToken]['code'] === T_VARIABLE) { + // We are only interested in function calls. + continue; + } + + $funcName = $tokens[$funcNameToken]['content']; + + // We've found the function, now we need to find it and see if it is + // public, private or protected. If it starts with an underscore we + // can assume it is private. + if ($funcName[0] === '_') { + continue; + } + + $foundCalls[$i] = [ + 'name' => $funcName, + 'type' => strtolower($tokens[$prevToken]['content']), + ]; + }//end for + + $errorClassName = substr($className, 0, -7); + + foreach ($foundCalls as $token => $funcData) { + if (isset($foundFunctions[$funcData['name']]) === false) { + // Function was not in this class, might have come from the parent. + // Either way, we can't really check this. + continue; + } else if ($foundFunctions[$funcData['name']] === 'public') { + $type = $funcData['type']; + $error = "Static calls to public methods in Action classes must not use the $type keyword; use %s::%s() instead"; + $data = [ + $errorClassName, + $funcName, + ]; + $phpcsFile->addError($error, $token, 'Found'.ucfirst($funcData['type']), $data); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeOwnSystemSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeOwnSystemSniff.php new file mode 100644 index 0000000..2ff91c9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeOwnSystemSniff.php @@ -0,0 +1,98 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Channels; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class IncludeOwnSystemSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DOUBLE_COLON]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $fileName = $phpcsFile->getFilename(); + $matches = []; + if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|i', $fileName, $matches) === 0) { + // Not an actions file. + return; + } + + $ownClass = $matches[2]; + $tokens = $phpcsFile->getTokens(); + + $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 2), null, false, true); + $typeName = trim($tokens[$typeName]['content'], " '"); + switch (strtolower($tokens[($stackPtr + 1)]['content'])) { + case 'includesystem' : + $included = strtolower($typeName); + break; + case 'includeasset' : + $included = strtolower($typeName).'assettype'; + break; + case 'includewidget' : + $included = strtolower($typeName).'widgettype'; + break; + default: + return; + } + + if ($included === strtolower($ownClass)) { + $error = "You do not need to include \"%s\" from within the system's own actions file"; + $data = [$ownClass]; + $phpcsFile->addError($error, $stackPtr, 'NotRequired', $data); + } + + }//end process() + + + /** + * Determines the included class name from given token. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param array $tokens The array of file tokens. + * @param int $stackPtr The position in the tokens array of the + * potentially included class. + * + * @return bool + */ + protected function getIncludedClassFromToken( + $phpcsFile, + array $tokens, + $stackPtr + ) { + + return false; + + }//end getIncludedClassFromToken() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeSystemSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeSystemSniff.php new file mode 100644 index 0000000..85d7f76 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeSystemSniff.php @@ -0,0 +1,314 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Channels; + +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class IncludeSystemSniff extends AbstractScopeSniff +{ + + /** + * A list of classes that don't need to be included. + * + * @var array + */ + private $ignore = [ + 'self' => true, + 'static' => true, + 'parent' => true, + 'channels' => true, + 'basesystem' => true, + 'dal' => true, + 'init' => true, + 'pdo' => true, + 'util' => true, + 'ziparchive' => true, + 'phpunit_framework_assert' => true, + 'abstractmysourceunittest' => true, + 'abstractdatacleanunittest' => true, + 'exception' => true, + 'abstractwidgetwidgettype' => true, + 'domdocument' => true, + ]; + + + /** + * Constructs an AbstractScopeSniff. + */ + public function __construct() + { + parent::__construct([T_FUNCTION], [T_DOUBLE_COLON, T_EXTENDS], true); + + }//end __construct() + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param integer $stackPtr The position where the token was found. + * @param integer $currScope The current scope opener token. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine the name of the class that the static function + // is being called on. + $classNameToken = $phpcsFile->findPrevious( + T_WHITESPACE, + ($stackPtr - 1), + null, + true + ); + + // Don't process class names represented by variables as this can be + // an inexact science. + if ($tokens[$classNameToken]['code'] === T_VARIABLE) { + return; + } + + $className = $tokens[$classNameToken]['content']; + if (isset($this->ignore[strtolower($className)]) === true) { + return; + } + + $includedClasses = []; + + $fileName = strtolower($phpcsFile->getFilename()); + $matches = []; + if (preg_match('|/systems/(.*)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) { + // This is an actions file, which means we don't + // have to include the system in which it exists. + $includedClasses[$matches[2]] = true; + + // Or a system it implements. + $class = $phpcsFile->getCondition($stackPtr, T_CLASS); + $implements = $phpcsFile->findNext(T_IMPLEMENTS, $class, ($class + 10)); + if ($implements !== false) { + $implementsClass = $phpcsFile->findNext(T_STRING, $implements); + $implementsClassName = strtolower($tokens[$implementsClass]['content']); + if (substr($implementsClassName, -7) === 'actions') { + $includedClasses[substr($implementsClassName, 0, -7)] = true; + } + } + } + + // Go searching for includeSystem and includeAsset calls within this + // function, or the inclusion of .inc files, which + // would be library files. + for ($i = ($currScope + 1); $i < $stackPtr; $i++) { + $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i); + if ($name !== false) { + $includedClasses[$name] = true; + // Special case for Widgets cause they are, well, special. + } else if (strtolower($tokens[$i]['content']) === 'includewidget') { + $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1)); + $typeName = trim($tokens[$typeName]['content'], " '"); + $includedClasses[strtolower($typeName).'widgettype'] = true; + } + } + + // Now go searching for includeSystem, includeAsset or require/include + // calls outside our scope. If we are in a class, look outside the + // class. If we are not, look outside the function. + $condPtr = $currScope; + if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) { + foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) { + if ($condType === T_CLASS) { + break; + } + } + } + + for ($i = 0; $i < $condPtr; $i++) { + // Skip other scopes. + if (isset($tokens[$i]['scope_closer']) === true) { + $i = $tokens[$i]['scope_closer']; + continue; + } + + $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i); + if ($name !== false) { + $includedClasses[$name] = true; + } + } + + // If we are in a testing class, we might have also included + // some systems and classes in our setUp() method. + $setupFunction = null; + if ($phpcsFile->hasCondition($stackPtr, T_CLASS) === true) { + foreach ($tokens[$stackPtr]['conditions'] as $condPtr => $condType) { + if ($condType === T_CLASS) { + // Is this is a testing class? + $name = $phpcsFile->findNext(T_STRING, $condPtr); + $name = $tokens[$name]['content']; + if (substr($name, -8) === 'UnitTest') { + // Look for a method called setUp(). + $end = $tokens[$condPtr]['scope_closer']; + $function = $phpcsFile->findNext(T_FUNCTION, ($condPtr + 1), $end); + while ($function !== false) { + $name = $phpcsFile->findNext(T_STRING, $function); + if ($tokens[$name]['content'] === 'setUp') { + $setupFunction = $function; + break; + } + + $function = $phpcsFile->findNext(T_FUNCTION, ($function + 1), $end); + } + } + } + }//end foreach + }//end if + + if ($setupFunction !== null) { + $start = ($tokens[$setupFunction]['scope_opener'] + 1); + $end = $tokens[$setupFunction]['scope_closer']; + for ($i = $start; $i < $end; $i++) { + $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i); + if ($name !== false) { + $includedClasses[$name] = true; + } + } + }//end if + + if (isset($includedClasses[strtolower($className)]) === false) { + $error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once'; + $data = [$className]; + $phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data); + } + + }//end processTokenWithinScope() + + + /** + * Processes a token within the scope that this test is listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * this token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_EXTENDS) { + // Find the class name. + $classNameToken = $phpcsFile->findNext(T_STRING, ($stackPtr + 1)); + $className = $tokens[$classNameToken]['content']; + } else { + // Determine the name of the class that the static function + // is being called on. But don't process class names represented by + // variables as this can be an inexact science. + $classNameToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$classNameToken]['code'] === T_VARIABLE) { + return; + } + + $className = $tokens[$classNameToken]['content']; + } + + // Some systems are always available. + if (isset($this->ignore[strtolower($className)]) === true) { + return; + } + + $includedClasses = []; + + $fileName = strtolower($phpcsFile->getFilename()); + $matches = []; + if (preg_match('|/systems/([^/]+)/([^/]+)?actions.inc$|', $fileName, $matches) !== 0) { + // This is an actions file, which means we don't + // have to include the system in which it exists + // We know the system from the path. + $includedClasses[$matches[1]] = true; + } + + // Go searching for includeSystem, includeAsset or require/include + // calls outside our scope. + for ($i = 0; $i < $stackPtr; $i++) { + // Skip classes and functions as will we never get + // into their scopes when including this file, although + // we have a chance of getting into IF, WHILE etc. + if (($tokens[$i]['code'] === T_CLASS + || $tokens[$i]['code'] === T_INTERFACE + || $tokens[$i]['code'] === T_FUNCTION) + && isset($tokens[$i]['scope_closer']) === true + ) { + $i = $tokens[$i]['scope_closer']; + continue; + } + + $name = $this->getIncludedClassFromToken($phpcsFile, $tokens, $i); + if ($name !== false) { + $includedClasses[$name] = true; + // Special case for Widgets cause they are, well, special. + } else if (strtolower($tokens[$i]['content']) === 'includewidget') { + $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($i + 1)); + $typeName = trim($tokens[$typeName]['content'], " '"); + $includedClasses[strtolower($typeName).'widgettype'] = true; + } + }//end for + + if (isset($includedClasses[strtolower($className)]) === false) { + if ($tokens[$stackPtr]['code'] === T_EXTENDS) { + $error = 'Class extends non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once'; + $data = [$className]; + $phpcsFile->addError($error, $stackPtr, 'NotIncludedExtends', $data); + } else { + $error = 'Static method called on non-included class or system "%s"; include system with Channels::includeSystem() or include class with require_once'; + $data = [$className]; + $phpcsFile->addError($error, $stackPtr, 'NotIncludedCall', $data); + } + } + + }//end processTokenOutsideScope() + + + /** + * Determines the included class name from given token. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param array $tokens The array of file tokens. + * @param int $stackPtr The position in the tokens array of the + * potentially included class. + * + * @return string|false + */ + protected function getIncludedClassFromToken(File $phpcsFile, array $tokens, $stackPtr) + { + if (strtolower($tokens[$stackPtr]['content']) === 'includesystem') { + $systemName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1)); + $systemName = trim($tokens[$systemName]['content'], " '"); + return strtolower($systemName); + } else if (strtolower($tokens[$stackPtr]['content']) === 'includeasset') { + $typeName = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1)); + $typeName = trim($tokens[$typeName]['content'], " '"); + return strtolower($typeName).'assettype'; + } else if (isset(Tokens::$includeTokens[$tokens[$stackPtr]['code']]) === true) { + $filePath = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, ($stackPtr + 1)); + $filePath = $tokens[$filePath]['content']; + $filePath = trim($filePath, " '"); + $filePath = basename($filePath, '.inc'); + return strtolower($filePath); + } + + return false; + + }//end getIncludedClassFromToken() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/UnusedSystemSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/UnusedSystemSniff.php new file mode 100644 index 0000000..7f96051 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/UnusedSystemSniff.php @@ -0,0 +1,141 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Channels; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class UnusedSystemSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DOUBLE_COLON]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Check if this is a call to includeSystem, includeAsset or includeWidget. + $methodName = strtolower($tokens[($stackPtr + 1)]['content']); + if ($methodName === 'includesystem' + || $methodName === 'includeasset' + || $methodName === 'includewidget' + ) { + $systemName = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 3), null, true); + if ($systemName === false || $tokens[$systemName]['code'] !== T_CONSTANT_ENCAPSED_STRING) { + // Must be using a variable instead of a specific system name. + // We can't accurately check that. + return; + } + + $systemName = trim($tokens[$systemName]['content'], " '"); + } else { + return; + } + + if ($methodName === 'includeasset') { + $systemName .= 'assettype'; + } else if ($methodName === 'includewidget') { + $systemName .= 'widgettype'; + } + + $systemName = strtolower($systemName); + + // Now check if this system is used anywhere in this scope. + $level = $tokens[$stackPtr]['level']; + for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { + if ($tokens[$i]['level'] < $level) { + // We have gone out of scope. + // If the original include was inside an IF statement that + // is checking if the system exists, check the outer scope + // as well. + if ($tokens[$stackPtr]['level'] === $level) { + // We are still in the base level, so this is the first + // time we have got here. + $conditions = array_keys($tokens[$stackPtr]['conditions']); + if (empty($conditions) === false) { + $cond = array_pop($conditions); + if ($tokens[$cond]['code'] === T_IF) { + $i = $tokens[$cond]['scope_closer']; + $level--; + continue; + } + } + } + + break; + }//end if + + if ($tokens[$i]['code'] !== T_DOUBLE_COLON + && $tokens[$i]['code'] !== T_EXTENDS + && $tokens[$i]['code'] !== T_IMPLEMENTS + ) { + continue; + } + + switch ($tokens[$i]['code']) { + case T_DOUBLE_COLON: + $usedName = strtolower($tokens[($i - 1)]['content']); + if ($usedName === $systemName) { + // The included system was used, so it is fine. + return; + } + break; + case T_EXTENDS: + $classNameToken = $phpcsFile->findNext(T_STRING, ($i + 1)); + $className = strtolower($tokens[$classNameToken]['content']); + if ($className === $systemName) { + // The included system was used, so it is fine. + return; + } + break; + case T_IMPLEMENTS: + $endImplements = $phpcsFile->findNext([T_EXTENDS, T_OPEN_CURLY_BRACKET], ($i + 1)); + for ($x = ($i + 1); $x < $endImplements; $x++) { + if ($tokens[$x]['code'] === T_STRING) { + $className = strtolower($tokens[$x]['content']); + if ($className === $systemName) { + // The included system was used, so it is fine. + return; + } + } + } + break; + }//end switch + }//end for + + // If we get to here, the system was not use. + $error = 'Included system "%s" is never used'; + $data = [$systemName]; + $phpcsFile->addError($error, $stackPtr, 'Found', $data); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Commenting/FunctionCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Commenting/FunctionCommentSniff.php new file mode 100644 index 0000000..d5f09b6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Commenting/FunctionCommentSniff.php @@ -0,0 +1,84 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Commenting; + +use PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff as SquizFunctionCommentSniff; +use PHP_CodeSniffer\Util\Tokens; +use PHP_CodeSniffer\Files\File; + +class FunctionCommentSniff extends SquizFunctionCommentSniff +{ + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + parent::process($phpcsFile, $stackPtr); + + $tokens = $phpcsFile->getTokens(); + $find = Tokens::$methodPrefixes; + $find[] = T_WHITESPACE; + + $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG) { + return; + } + + $commentStart = $tokens[$commentEnd]['comment_opener']; + $hasApiTag = false; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@api') { + if ($hasApiTag === true) { + // We've come across an API tag already, which means + // we were not the first tag in the API list. + $error = 'The @api tag must come first in the @api tag list in a function comment'; + $phpcsFile->addError($error, $tag, 'ApiNotFirst'); + } + + $hasApiTag = true; + + // There needs to be a blank line before the @api tag. + $prev = $phpcsFile->findPrevious([T_DOC_COMMENT_STRING, T_DOC_COMMENT_TAG], ($tag - 1)); + if ($tokens[$prev]['line'] !== ($tokens[$tag]['line'] - 2)) { + $error = 'There must be one blank line before the @api tag in a function comment'; + $phpcsFile->addError($error, $tag, 'ApiSpacing'); + } + } else if (substr($tokens[$tag]['content'], 0, 5) === '@api-') { + $hasApiTag = true; + + $prev = $phpcsFile->findPrevious([T_DOC_COMMENT_STRING, T_DOC_COMMENT_TAG], ($tag - 1)); + if ($tokens[$prev]['line'] !== ($tokens[$tag]['line'] - 1)) { + $error = 'There must be no blank line before the @%s tag in a function comment'; + $data = [$tokens[$tag]['content']]; + $phpcsFile->addError($error, $tag, 'ApiTagSpacing', $data); + } + }//end if + }//end foreach + + if ($hasApiTag === true && substr($tokens[$tag]['content'], 0, 4) !== '@api') { + // API tags must be the last tags in a function comment. + $error = 'The @api tags must be the last tags in a function comment'; + $phpcsFile->addError($error, $commentEnd, 'ApiNotLast'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/DebugCodeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/DebugCodeSniff.php new file mode 100644 index 0000000..1ae6ba3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/DebugCodeSniff.php @@ -0,0 +1,55 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Debug; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class DebugCodeSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DOUBLE_COLON]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $className = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if (strtolower($tokens[$className]['content']) === 'debug') { + $method = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $error = 'Call to debug function Debug::%s() must be removed'; + $data = [$tokens[$method]['content']]; + $phpcsFile->addError($error, $stackPtr, 'Found', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/FirebugConsoleSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/FirebugConsoleSniff.php new file mode 100644 index 0000000..77b8666 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/FirebugConsoleSniff.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Debug; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class FirebugConsoleSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_STRING, + T_PROPERTY, + T_LABEL, + T_OBJECT, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (strtolower($tokens[$stackPtr]['content']) === 'console') { + $error = 'Variables, functions and labels must not be named "console"; name may conflict with Firebug internal variable'; + $phpcsFile->addError($error, $stackPtr, 'ConflictFound'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/AssignThisSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/AssignThisSniff.php new file mode 100644 index 0000000..a126dce --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/AssignThisSniff.php @@ -0,0 +1,81 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Objects; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class AssignThisSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_THIS]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore this.something and other uses of "this" that are not + // direct assignments. + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] !== T_SEMICOLON) { + if ($tokens[$next]['line'] === $tokens[$stackPtr]['line']) { + return; + } + } + + // Something must be assigned to "this". + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] !== T_EQUAL) { + return; + } + + // A variable needs to be assigned to "this". + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($prev - 1), null, true); + if ($tokens[$prev]['code'] !== T_STRING) { + return; + } + + // We can only assign "this" to a var called "self". + if ($tokens[$prev]['content'] !== 'self' && $tokens[$prev]['content'] !== '_self') { + $error = 'Keyword "this" can only be assigned to a variable called "self" or "_self"'; + $phpcsFile->addError($error, $prev, 'NotSelf'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/CreateWidgetTypeCallbackSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/CreateWidgetTypeCallbackSniff.php new file mode 100644 index 0000000..25e48dc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/CreateWidgetTypeCallbackSniff.php @@ -0,0 +1,218 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Objects; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class CreateWidgetTypeCallbackSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OBJECT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $className = $phpcsFile->findPrevious(T_STRING, ($stackPtr - 1)); + if (substr(strtolower($tokens[$className]['content']), -10) !== 'widgettype') { + return; + } + + // Search for a create method. + $create = $phpcsFile->findNext(T_PROPERTY, $stackPtr, $tokens[$stackPtr]['bracket_closer'], null, 'create'); + if ($create === false) { + return; + } + + $function = $phpcsFile->findNext([T_WHITESPACE, T_COLON], ($create + 1), null, true); + if ($tokens[$function]['code'] !== T_FUNCTION + && $tokens[$function]['code'] !== T_CLOSURE + ) { + return; + } + + $start = ($tokens[$function]['scope_opener'] + 1); + $end = ($tokens[$function]['scope_closer'] - 1); + + // Check that the first argument is called "callback". + $arg = $phpcsFile->findNext(T_WHITESPACE, ($tokens[$function]['parenthesis_opener'] + 1), null, true); + if ($tokens[$arg]['content'] !== 'callback') { + $error = 'The first argument of the create() method of a widget type must be called "callback"'; + $phpcsFile->addError($error, $arg, 'FirstArgNotCallback'); + } + + /* + Look for return statements within the function. They cannot return + anything and must be preceded by the callback.call() line. The + callback itself must contain "self" or "this" as the first argument + and there needs to be a call to the callback function somewhere + in the create method. All calls to the callback function must be + followed by a return statement or the end of the method. + */ + + $foundCallback = false; + $passedCallback = false; + $nestedFunction = null; + for ($i = $start; $i <= $end; $i++) { + // Keep track of nested functions. + if ($nestedFunction !== null) { + if ($i === $nestedFunction) { + $nestedFunction = null; + continue; + } + } else if (($tokens[$i]['code'] === T_FUNCTION + || $tokens[$i]['code'] === T_CLOSURE) + && isset($tokens[$i]['scope_closer']) === true + ) { + $nestedFunction = $tokens[$i]['scope_closer']; + continue; + } + + if ($nestedFunction === null && $tokens[$i]['code'] === T_RETURN) { + // Make sure return statements are not returning anything. + if ($tokens[($i + 1)]['code'] !== T_SEMICOLON) { + $error = 'The create() method of a widget type must not return a value'; + $phpcsFile->addError($error, $i, 'ReturnValue'); + } + + continue; + } else if ($tokens[$i]['code'] !== T_STRING + || $tokens[$i]['content'] !== 'callback' + ) { + continue; + } + + // If this is the form "callback.call(" then it is a call + // to the callback function. + if ($tokens[($i + 1)]['code'] !== T_OBJECT_OPERATOR + || $tokens[($i + 2)]['content'] !== 'call' + || $tokens[($i + 3)]['code'] !== T_OPEN_PARENTHESIS + ) { + // One last chance; this might be the callback function + // being passed to another function, like this + // "this.init(something, callback, something)". + if (isset($tokens[$i]['nested_parenthesis']) === false) { + continue; + } + + // Just make sure those brackets don't belong to anyone, + // like an IF or FOR statement. + foreach ($tokens[$i]['nested_parenthesis'] as $bracket) { + if (isset($tokens[$bracket]['parenthesis_owner']) === true) { + continue(2); + } + } + + // Note that we use this endBracket down further when checking + // for a RETURN statement. + $nestedParens = $tokens[$i]['nested_parenthesis']; + $endBracket = end($nestedParens); + $bracket = key($nestedParens); + + $prev = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($bracket - 1), + null, + true + ); + + if ($tokens[$prev]['code'] !== T_STRING) { + // This is not a function passing the callback. + continue; + } + + $passedCallback = true; + }//end if + + $foundCallback = true; + + if ($passedCallback === false) { + // The first argument must be "this" or "self". + $arg = $phpcsFile->findNext(T_WHITESPACE, ($i + 4), null, true); + if ($tokens[$arg]['content'] !== 'this' + && $tokens[$arg]['content'] !== 'self' + ) { + $error = 'The first argument passed to the callback function must be "this" or "self"'; + $phpcsFile->addError($error, $arg, 'FirstArgNotSelf'); + } + } + + // Now it must be followed by a return statement or the end of the function. + if ($passedCallback === false) { + $endBracket = $tokens[($i + 3)]['parenthesis_closer']; + } + + for ($next = $endBracket; $next <= $end; $next++) { + // Skip whitespace so we find the next content after the call. + if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === true) { + continue; + } + + // Skip closing braces like END IF because it is not executable code. + if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) { + continue; + } + + // We don't care about anything on the current line, like a + // semicolon. It doesn't matter if there are other statements on the + // line because another sniff will check for those. + if ($tokens[$next]['line'] === $tokens[$endBracket]['line']) { + continue; + } + + break; + } + + if ($next !== $tokens[$function]['scope_closer'] + && $tokens[$next]['code'] !== T_RETURN + ) { + $error = 'The call to the callback function must be followed by a return statement if it is not the last statement in the create() method'; + $phpcsFile->addError($error, $i, 'NoReturn'); + } + }//end for + + if ($foundCallback === false) { + $error = 'The create() method of a widget type must call the callback function'; + $phpcsFile->addError($error, $create, 'CallbackNotCalled'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/DisallowNewWidgetSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/DisallowNewWidgetSniff.php new file mode 100644 index 0000000..ecb57e5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/DisallowNewWidgetSniff.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Objects; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class DisallowNewWidgetSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_NEW]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $className = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$className]['code'] !== T_STRING) { + return; + } + + if (substr(strtolower($tokens[$className]['content']), -10) === 'widgettype') { + $widgetType = substr($tokens[$className]['content'], 0, -10); + $error = 'Manual creation of widget objects is banned; use Widget::getWidget(\'%s\'); instead'; + $data = [$widgetType]; + $phpcsFile->addError($error, $stackPtr, 'Found', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/AjaxNullComparisonSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/AjaxNullComparisonSniff.php new file mode 100644 index 0000000..71c31da --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/AjaxNullComparisonSniff.php @@ -0,0 +1,103 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\PHP; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class AjaxNullComparisonSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Make sure it is an API function. We know this by the doc comment. + $commentEnd = $phpcsFile->findPrevious(T_DOC_COMMENT_CLOSE_TAG, $stackPtr); + $commentStart = $phpcsFile->findPrevious(T_DOC_COMMENT_OPEN_TAG, ($commentEnd - 1)); + // If function doesn't contain any doc comments - skip it. + if ($commentEnd === false || $commentStart === false) { + return; + } + + $comment = $phpcsFile->getTokensAsString($commentStart, ($commentEnd - $commentStart)); + if (strpos($comment, '* @api') === false) { + return; + } + + // Find all the vars passed in as we are only interested in comparisons + // to NULL for these specific variables. + $foundVars = []; + $open = $tokens[$stackPtr]['parenthesis_opener']; + $close = $tokens[$stackPtr]['parenthesis_closer']; + for ($i = ($open + 1); $i < $close; $i++) { + if ($tokens[$i]['code'] === T_VARIABLE) { + $foundVars[$tokens[$i]['content']] = true; + } + } + + if (empty($foundVars) === true) { + return; + } + + $start = $tokens[$stackPtr]['scope_opener']; + $end = $tokens[$stackPtr]['scope_closer']; + for ($i = ($start + 1); $i < $end; $i++) { + if ($tokens[$i]['code'] !== T_VARIABLE + || isset($foundVars[$tokens[$i]['content']]) === false + ) { + continue; + } + + $operator = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true); + if ($tokens[$operator]['code'] !== T_IS_IDENTICAL + && $tokens[$operator]['code'] !== T_IS_NOT_IDENTICAL + ) { + continue; + } + + $nullValue = $phpcsFile->findNext(T_WHITESPACE, ($operator + 1), null, true); + if ($tokens[$nullValue]['code'] !== T_NULL) { + continue; + } + + $error = 'Values submitted via Ajax requests should not be compared directly to NULL; use empty() instead'; + $phpcsFile->addWarning($error, $nullValue, 'Found'); + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/EvalObjectFactorySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/EvalObjectFactorySniff.php new file mode 100644 index 0000000..3b775af --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/EvalObjectFactorySniff.php @@ -0,0 +1,114 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\PHP; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class EvalObjectFactorySniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_EVAL]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + /* + We need to find all strings that will be in the eval + to determine if the "new" keyword is being used. + */ + + $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($stackPtr + 1)); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + $strings = []; + $vars = []; + + for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { + if (isset(Tokens::$stringTokens[$tokens[$i]['code']]) === true) { + $strings[$i] = $tokens[$i]['content']; + } else if ($tokens[$i]['code'] === T_VARIABLE) { + $vars[$i] = $tokens[$i]['content']; + } + } + + /* + We now have some variables that we need to expand into + the strings that were assigned to them, if any. + */ + + foreach ($vars as $varPtr => $varName) { + while (($prev = $phpcsFile->findPrevious(T_VARIABLE, ($varPtr - 1))) !== false) { + // Make sure this is an assignment of the variable. That means + // it will be the first thing on the line. + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($prev - 1), null, true); + if ($tokens[$prevContent]['line'] === $tokens[$prev]['line']) { + $varPtr = $prevContent; + continue; + } + + if ($tokens[$prev]['content'] !== $varName) { + // This variable has a different name. + $varPtr = $prevContent; + continue; + } + + // We found one. + break; + }//end while + + if ($prev !== false) { + // Find all strings on the line. + $lineEnd = $phpcsFile->findNext(T_SEMICOLON, ($prev + 1)); + for ($i = ($prev + 1); $i < $lineEnd; $i++) { + if (isset(Tokens::$stringTokens[$tokens[$i]['code']]) === true) { + $strings[$i] = $tokens[$i]['content']; + } + } + } + }//end foreach + + foreach ($strings as $string) { + // If the string has "new" in it, it is not allowed. + // We don't bother checking if the word "new" is printed to screen + // because that is unlikely to happen. We assume the use + // of "new" is for object instantiation. + if (strstr($string, ' new ') !== false) { + $error = 'Do not use eval() to create objects dynamically; use reflection instead'; + $phpcsFile->addWarning($error, $stackPtr, 'Found'); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/GetRequestDataSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/GetRequestDataSniff.php new file mode 100644 index 0000000..bdb3452 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/GetRequestDataSniff.php @@ -0,0 +1,106 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\PHP; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class GetRequestDataSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_VARIABLE]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $varName = $tokens[$stackPtr]['content']; + if ($varName !== '$_REQUEST' + && $varName !== '$_GET' + && $varName !== '$_POST' + && $varName !== '$_FILES' + ) { + return; + } + + // The only place these super globals can be accessed directly is + // in the getRequestData() method of the Security class. + $inClass = false; + foreach ($tokens[$stackPtr]['conditions'] as $i => $type) { + if ($tokens[$i]['code'] === T_CLASS) { + $className = $phpcsFile->findNext(T_STRING, $i); + $className = $tokens[$className]['content']; + if (strtolower($className) === 'security') { + $inClass = true; + } else { + // We don't have nested classes. + break; + } + } else if ($inClass === true && $tokens[$i]['code'] === T_FUNCTION) { + $funcName = $phpcsFile->findNext(T_STRING, $i); + $funcName = $tokens[$funcName]['content']; + if (strtolower($funcName) === 'getrequestdata') { + // This is valid. + return; + } else { + // We don't have nested functions. + break; + } + }//end if + }//end foreach + + // If we get to here, the super global was used incorrectly. + // First find out how it is being used. + $globalName = strtolower(substr($varName, 2)); + $usedVar = ''; + + $openBracket = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$openBracket]['code'] === T_OPEN_SQUARE_BRACKET) { + $closeBracket = $tokens[$openBracket]['bracket_closer']; + $usedVar = $phpcsFile->getTokensAsString(($openBracket + 1), ($closeBracket - $openBracket - 1)); + } + + $type = 'SuperglobalAccessed'; + $error = 'The %s super global must not be accessed directly; use Security::getRequestData('; + $data = [$varName]; + if ($usedVar !== '') { + $type .= 'WithVar'; + $error .= '%s, \'%s\''; + $data[] = $usedVar; + $data[] = $globalName; + } + + $error .= ') instead'; + $phpcsFile->addError($error, $stackPtr, $type, $data); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/ReturnFunctionValueSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/ReturnFunctionValueSniff.php new file mode 100644 index 0000000..1696837 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/ReturnFunctionValueSniff.php @@ -0,0 +1,63 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\PHP; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; + +class ReturnFunctionValueSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_RETURN]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $functionName = $phpcsFile->findNext(T_STRING, ($stackPtr + 1), null, false, null, true); + + while ($functionName !== false) { + // Check if this is really a function. + $bracket = $phpcsFile->findNext(T_WHITESPACE, ($functionName + 1), null, true); + if ($tokens[$bracket]['code'] !== T_OPEN_PARENTHESIS) { + // Not a function call. + $functionName = $phpcsFile->findNext(T_STRING, ($functionName + 1), null, false, null, true); + continue; + } + + $error = 'The result of a function call should be assigned to a variable before being returned'; + $phpcsFile->addWarning($error, $stackPtr, 'NotAssigned'); + break; + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Strings/JoinStringsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Strings/JoinStringsSniff.php new file mode 100644 index 0000000..968873e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Strings/JoinStringsSniff.php @@ -0,0 +1,76 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Sniffs\Strings; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class JoinStringsSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_STRING]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param integer $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['content'] !== 'join') { + return; + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] !== T_OBJECT_OPERATOR) { + return; + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true); + if ($tokens[$prev]['code'] === T_CLOSE_SQUARE_BRACKET) { + $opener = $tokens[$prev]['bracket_opener']; + if ($tokens[($opener - 1)]['code'] !== T_STRING) { + // This means the array is declared inline, like x = [a,b,c].join() + // and not elsewhere, like x = y[a].join() + // The first is not allowed while the second is. + $error = 'Joining strings using inline arrays is not allowed; use the + operator instead'; + $phpcsFile->addError($error, $stackPtr, 'ArrayNotAllowed'); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.css new file mode 100644 index 0000000..339ee15 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.css @@ -0,0 +1,13 @@ +.SettingsTabPaneWidgetType-tab-mid { + background: transparent url(tab_inact_mid.png) repeat-x; + line-height: -25px; + cursor: pointer; + -moz-user-select: none; +} + +.AssetLineageWidgetType-item { + float: left; + list-style: none; + height: 22px; + cursor: pointer; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.php new file mode 100644 index 0000000..3004959 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/CSS/BrowserSpecificStylesUnitTest.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the BrowserSpecificStyles sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\CSS\BrowserSpecificStylesSniff + */ +class BrowserSpecificStylesUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [5 => 1]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.inc new file mode 100644 index 0000000..95fd04b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.inc @@ -0,0 +1,51 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.php new file mode 100644 index 0000000..9233a2f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/DisallowSelfActionsUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Channels; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowSelfActions sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Channels\DisallowSelfActionsSniff + */ +class DisallowSelfActionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 12 => 1, + 13 => 1, + 28 => 1, + 29 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.inc new file mode 100644 index 0000000..ccb0273 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.inc @@ -0,0 +1,112 @@ +fetch(PDO::FETCH_NUM) +BaseSystem::getDataDir(); +Util::getArrayIndex(array(), ''); + + +Channels::includeSystem('Widget'); +Widget::includeWidget('AbstractContainer'); +class MyWidget extends AbstractContainerWidgetType {} +class MyOtherWidget extends BookWidgetType {} + +$zip = new ZipArchive(); +$res = $zip->open($path, ZipArchive::CREATE); + +class AssetListingUnitTest extends AbstractMySourceUnitTest +{ + function setUp() { + parent::setUp(); + Channels::includeSystem('MySystem2'); + include_once 'Libs/FileSystem.inc'; + } + + function two() { + $siteid = MySystem2::getCurrentSiteId(); + $parserFiles = FileSystem::listDirectory(); + } + + function three() { + $siteid = MySystem3::getCurrentSiteId(); + $parserFiles = FileSystem::listDirectory(); + } +} + +if (Channels::systemExists('Log') === TRUE) { + Channels::includeSystem('Log'); +} else { + return; +} + +Log::addProjectLog('metadata.field.update', $msg); + +function two() { + Widget::includeWidget('CacheAdminScreen'); + $barChart = CacheAdminScreenWidgetType::constructBarchart($data); +} + +$adjustDialog->setOrientation(AbstractWidgetWidgetType::CENTER); + +$className = 'SquizPerspective'.ucfirst($property['type']).'PropertyType'; +Channels::includeSystem($className); +$className::setValue($assetid, $propertyid, $perspectives, $value, (array) $property['settings']); +?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.php new file mode 100644 index 0000000..4075356 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/IncludeSystemUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Channels; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the IncludeSystem sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Channels\IncludeSystemSniff + */ +class IncludeSystemUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 14 => 1, + 24 => 1, + 27 => 1, + 28 => 1, + 31 => 1, + 36 => 1, + 41 => 1, + 61 => 1, + 70 => 1, + 89 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.inc new file mode 100644 index 0000000..c7bd473 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.inc @@ -0,0 +1,67 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.php new file mode 100644 index 0000000..b3455ac --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Channels/UnusedSystemUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Channels; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the UnusedSystem sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Channels\UnusedSystemSniff + */ +class UnusedSystemUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 5 => 1, + 8 => 1, + 24 => 1, + 34 => 1, + 54 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.inc new file mode 100644 index 0000000..19d5c5d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.inc @@ -0,0 +1,101 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.php new file mode 100644 index 0000000..8a3d706 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Commenting/FunctionCommentUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionComment sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Commenting\FunctionCommentSniff + */ +class FunctionCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 28 => 1, + 36 => 1, + 37 => 2, + 49 => 1, + 58 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.inc new file mode 100644 index 0000000..3490161 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.inc @@ -0,0 +1,4 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.php new file mode 100644 index 0000000..d8f8011 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/DebugCodeUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Debug; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DebugCode sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Debug\DebugCodeSniff + */ +class DebugCodeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 3 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.js new file mode 100644 index 0000000..d5e3df5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.js @@ -0,0 +1,8 @@ +console.info(); +console.warn(); +console.test(); +con.sole(); +var console = { + console: 'string'; +}; +function console() {} \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.php new file mode 100644 index 0000000..3a88a0e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Debug/FirebugConsoleUnitTest.php @@ -0,0 +1,66 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Debug; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FirebugConsole sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Debug\FirebugConsoleSniff + */ +class FirebugConsoleUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile !== 'FirebugConsoleUnitTest.js') { + return []; + } + + return [ + 1 => 1, + 2 => 1, + 3 => 1, + 5 => 1, + 6 => 1, + 8 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.js new file mode 100644 index 0000000..747a100 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.js @@ -0,0 +1,20 @@ +var self = this; +buttonWidget.addClickEvent(function() { + self.addDynamicSouce(); +}); + +var x = self; +var y = this; + +var test = ''; +if (true) { + test = this +} + +var itemid = this.items[i].getAttribute('itemid'); + +for (var x = this; y < 10; y++) { + var x = this + 1; +} + +var _self = this; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.php new file mode 100644 index 0000000..4b056a7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/AssignThisUnitTest.php @@ -0,0 +1,63 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the AssignThis sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Objects\AssignThisSniff + */ +class AssignThisUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile !== 'AssignThisUnitTest.js') { + return []; + } + + return [ + 7 => 1, + 11 => 1, + 16 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.js new file mode 100644 index 0000000..22822d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.js @@ -0,0 +1,186 @@ +SampleWidgetType.prototype = { + + create: function(callback) + { + if (x === 1) { + return; + } + + if (y === 1) { + callback.call(this); + // A comment here to explain the return is okay. + return; + } + + if (a === 1) { + // Cant return value even after calling callback. + callback.call(this); + return something; + } + + if (a === 1) { + // Need to pass self or this to callback function. + callback.call(a); + } + + callback.call(self); + + var self = this; + this.createChildren(null, function() { + callback.call(self, div); + }); + + // Never good to return a value. + return something; + + callback.call(self); + } + +}; + +AnotherSampleWidgetType.prototype = { + + create: function(input) + { + return; + } + + getSomething: function(input) + { + return 1; + } + +}; + + +NoCreateWidgetType.prototype = { + + getSomething: function(input) + { + return; + } + +}; + + +SomeRandom.prototype = { + + create: function(input) + { + return; + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + if (a === 1) { + // This is ok because it is the last statement, + // even though it is conditional. + callback.call(self); + } + + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + var something = callback; + + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + // Also valid because we are passing the callback to + // someone else to call. + if (y === 1) { + this.something(callback); + return; + } + + this.init(callback); + + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + // Also valid because we are passing the callback to + // someone else to call. + if (y === 1) { + this.something(callback); + } + + this.init(callback); + + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + if (a === 1) { + // This is ok because it is the last statement, + // even though it is conditional. + this.something(callback); + } + + } + +}; + + +SampleWidgetType.prototype = { + + create: function(callback) + { + if (dfx.isFn(callback) === true) { + callback.call(this, cont); + return; + } + } + +}; + + +SampleWidgetType.prototype = { + + create: function(callback) + { + dfx.foreach(items, function(item) { + return true; + }); + + if (dfx.isFn(callback) === true) { + callback.call(this); + } + } + +}; + +SampleWidgetType.prototype = { + + create: function(callback) + { + var self = this; + this.createChildren(null, function() { + callback.call(self, div); + return; + }); + } + +}; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.php new file mode 100644 index 0000000..55b9337 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/CreateWidgetTypeCallbackUnitTest.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the CreateWidgetTypeCallback sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Objects\CreateWidgetTypeCallbackSniff + */ +class CreateWidgetTypeCallbackUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 18 => 1, + 23 => 2, + 26 => 1, + 30 => 1, + 34 => 1, + 43 => 2, + 91 => 1, + 123 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.inc new file mode 100644 index 0000000..acf9baf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.inc @@ -0,0 +1,6 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.php new file mode 100644 index 0000000..3fa2453 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Objects/DisallowNewWidgetUnitTest.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowNewWidget sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Objects\DisallowNewWidgetSniff + */ +class DisallowNewWidgetUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [4 => 1]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.inc new file mode 100644 index 0000000..337914a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.inc @@ -0,0 +1,182 @@ +getMessage()); + }//end try + + if ($something === NULL) { + if ($bar !== NULL) { + } + } + + return $issueid; + +}//end addIssue() + +/** + * Adds a new issue. + * + * Returns the new issue id. + * + * @param string $title Title of the new issue. + * @param string $description The description of the issue. + * @param string $reporter Asset id of the reporter. + * @param integer $projectid Id of the project that the issue belongs to. + * @param array $tags Array of tags. + * @param string $status The status of the issue. + * @param string $assignedTo The asset id of the user that the issue is + * assigned to. + * @param string $reportedDate If set then this date will be used instead of the + * current date and time. + * @param integer $reportedMilestone Reported milestone. + * + * @return integer + * @throws ChannelException If there is an error. + * + */ +public static function addIssue( + $title, + $description, + $reporter=NULL, + $projectid=NULL, + array $tags=array(), + $status=NULL, + $assignedTo=NULL, + $reportedDate=NULL, + $reportedMilestone=NULL +) { + // Get current projectid if not specified. + if ($projectid === NULL) { + Channels::includeSystem('Project'); + $projectid = Project::getCurrentProjectId(); + Channels::modifyBasket('project', $projectid); + } + +}//end addIssue() diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.php new file mode 100644 index 0000000..606b9f4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/AjaxNullComparisonUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the AjaxNullComparison sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\PHP\AjaxNullComparisonSniff + */ +class AjaxNullComparisonUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 41 => 1, + 53 => 1, + 64 => 1, + 77 => 1, + 92 => 1, + 122 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.inc new file mode 100644 index 0000000..992a7dc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.inc @@ -0,0 +1,26 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.php new file mode 100644 index 0000000..85a8c3c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/EvalObjectFactoryUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EvalObjectFactory sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\PHP\EvalObjectFactorySniff + */ +class EvalObjectFactoryUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 4 => 1, + 12 => 1, + 21 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.inc new file mode 100644 index 0000000..7999763 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.inc @@ -0,0 +1,30 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.php new file mode 100644 index 0000000..747fae1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/GetRequestDataUnitTest.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the GetRequestData sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\PHP\GetRequestDataSniff + */ +class GetRequestDataUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 5 => 1, + 8 => 1, + 21 => 1, + 26 => 1, + 27 => 1, + 28 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.inc new file mode 100644 index 0000000..f9148a7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.inc @@ -0,0 +1,9 @@ +myFunction(); +return $obj->variable; +return MyClass::VARIABLE; +return $variable; +return ($var + 1); +?> \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.php new file mode 100644 index 0000000..3859a03 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/PHP/ReturnFunctionValueUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ReturnFunctionValue sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\PHP\ReturnFunctionValueSniff + */ +class ReturnFunctionValueUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 2 => 1, + 3 => 1, + 4 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.js new file mode 100644 index 0000000..46d90cf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.js @@ -0,0 +1,18 @@ +one = (1 + 2); +two = (one + 2); +two = (one + one); +three = ('1' + 2); + +four = ['1', two].join(); +four = ['1', two].join(''); +four = ['1', [one, two].join(',')].join(' '); +four = ['1', [one, two].join()].join(' '); +four = ['1', [one, two].join()].join(); + +five = 'string' + ['1', [one, two].join()].join() + 'string'; + +six = myArray.join(' '); +six = [arrayOne, arrayTwo].join(); + +// This is fine because the array is not created inline. +var x = 'x' + test[x].join('p') + 't'; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.php new file mode 100644 index 0000000..a2c43dc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests/Strings/JoinStringsUnitTest.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\MySource\Tests\Strings; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the JoinStrings sniff. + * + * @covers PHP_CodeSniffer\Standards\MySource\Sniffs\Strings\JoinStringsSniff + */ +class JoinStringsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile !== 'JoinStringsUnitTest.js') { + return []; + } + + return [ + 6 => 1, + 7 => 1, + 8 => 2, + 9 => 2, + 10 => 2, + 12 => 2, + 15 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/MySource/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/ruleset.xml new file mode 100644 index 0000000..9240795 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/MySource/ruleset.xml @@ -0,0 +1,18 @@ + + + The MySource coding standard builds on the Squiz coding standard. Currently used for MySource Mini development. + + */Tests/* + */Oven/* + */data/* + */jquery.js + */jquery.*.js + */viper/* + DALConf.inc + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Classes/ClassDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Classes/ClassDeclarationStandard.xml new file mode 100644 index 0000000..b5d53fd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Classes/ClassDeclarationStandard.xml @@ -0,0 +1,22 @@ + + + + + + + { +} + ]]> + + + { +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/ClassCommentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/ClassCommentStandard.xml new file mode 100644 index 0000000..fe81620 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/ClassCommentStandard.xml @@ -0,0 +1,177 @@ + + + + + + + /** + * The Foo class. + */ +class Foo +{ +} + ]]> + + + + + + + + /** + * The Foo class. + */ +class Foo +{ +} + ]]> + + + + + + + + /** + * The Foo class. + */ +class Foo +{ +} + ]]> + + + /** + * The Foo class. + */ + +class Foo +{ +} + ]]> + + + + + The Foo class. + */ +class Foo +{ +} + ]]> + + + The Foo class. + */ +class Foo +{ +} + ]]> + + + + + + * A helper for the Bar class. + * + * @see Bar + */ +class Foo +{ +} + ]]> + + + + * + * A helper for the Bar class. + * + * + * @see Bar + */ +class Foo +{ +} + ]]> + + + + + + * @see Bar + */ +class Foo +{ +} + ]]> + + + + * + * @see Bar + */ +class Foo +{ +} + ]]> + + + + + Release: 1.0 + */ +class Foo +{ +} + ]]> + + + 1.0 + */ +class Foo +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FileCommentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FileCommentStandard.xml new file mode 100644 index 0000000..eef0b4e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FileCommentStandard.xml @@ -0,0 +1,286 @@ + + + + + + + /** + * Short description here. + * + * PHP version 5 + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + ]]> + + + + + Short description here. + * + * PHP version 5 + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + * Short description here. + * + * PHP version 5 + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + + * PHP version 5 + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + * + * PHP version 5 + * + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + + + + @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + @category Foo + * @category Bar + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + PHP version 5 + * + * @category Foo + * @package Foo_Helpers + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + @package Foo_Helpers + * @category Foo + * @author Marty McFly + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + + + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + + * @copyright 2013-2014 Foo Inc. + * @license MIT License + * @link http://example.com + */ + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FunctionCommentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FunctionCommentStandard.xml new file mode 100644 index 0000000..621649f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FunctionCommentStandard.xml @@ -0,0 +1,230 @@ + + + + + + + /** + * Short description here. + * + * @return void + */ + function foo() + { + } + ]]> + + + + + + + + Short description here. + * + * @return void + */ + function foo() + { + } + ]]> + + + + * Short description here. + * + * @return void + */ + function foo() + { + } + ]]> + + + + + + * Long description here. + * + * @return void + */ + function foo() + { + } + ]]> + + + + * + * Long description here. + * + * + * @return void + */ + function foo() + { + } + ]]> + + + + + + * @return void + */ + function foo() + { + } + ]]> + + + + * + * @return void + */ + function foo() + { + } + ]]> + + + + + FooException + */ + function foo() + { + } + ]]> + + + @throws + */ + function foo() + { + } + ]]> + + + + + @return void + */ + function foo() + { + } + ]]> + + + + + + + + $foo Foo parameter + * @param string $bar Bar parameter + * @return void + */ + function foo($foo, $bar) + { + } + ]]> + + + $qux Bar parameter + * @return void + */ + function foo($foo, $bar) + { + } + ]]> + + + + + $foo Foo parameter + * @param string $bar Bar parameter + * @return void + */ + function foo($foo, $bar) + { + } + ]]> + + + $bar Bar parameter + * @param string $foo Foo parameter + * @return void + */ + function foo($foo, $bar) + { + } + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/InlineCommentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/InlineCommentStandard.xml new file mode 100644 index 0000000..53056e2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/InlineCommentStandard.xml @@ -0,0 +1,19 @@ + + + + + + + // A comment. + ]]> + + + # A comment. + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/ControlSignatureStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/ControlSignatureStandard.xml new file mode 100644 index 0000000..ce430fb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/ControlSignatureStandard.xml @@ -0,0 +1,36 @@ + + + + + + + ($foo) { +} + ]]> + + + ($foo){ +} + ]]> + + + + + { +} + ]]> + + + { +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/MultiLineConditionStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/MultiLineConditionStandard.xml new file mode 100644 index 0000000..96d451d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/MultiLineConditionStandard.xml @@ -0,0 +1,60 @@ + + + + + + + && $bar +) { +} + ]]> + + + && $bar +) { +} + ]]> + + + + + && $bar +) { +} + ]]> + + + && + $bar +) { +} + ]]> + + + + + ) { +} + ]]> + + + ) { +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/IncludingFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/IncludingFileStandard.xml new file mode 100644 index 0000000..6d115be --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/IncludingFileStandard.xml @@ -0,0 +1,24 @@ + + + require_once. Anywhere you are conditionally including a class file (for example, factory methods), use include_once. Either of these will ensure that class files are included only once. They share the same file list, so you don't need to worry about mixing them - a file included with require_once will not be included again by include_once. + ]]> + + + include_once and require_once are statements, not functions. Parentheses should not surround the subject filename. + ]]> + + + + + + + ('PHP/CodeSniffer.php'); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/LineLengthStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/LineLengthStandard.xml new file mode 100644 index 0000000..e4911ef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/LineLengthStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Formatting/MultiLineAssignmentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Formatting/MultiLineAssignmentStandard.xml new file mode 100644 index 0000000..e825c55 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Formatting/MultiLineAssignmentStandard.xml @@ -0,0 +1,35 @@ + + + + + + + = $bar; + ]]> + + + = + $bar; + ]]> + + + + + = $bar; + ]]> + + + = $bar; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionCallSignatureStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionCallSignatureStandard.xml new file mode 100644 index 0000000..f874227 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionCallSignatureStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + ( $bar, $baz, $quux ) ; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionDeclarationStandard.xml new file mode 100644 index 0000000..ced9ae2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionDeclarationStandard.xml @@ -0,0 +1,41 @@ + + + + + + + () use ($bar) { +}; + ]]> + + + ()use($bar){ +}; + ]]> + + + + + $bar, + $baz +) { +}; + ]]> + + + $bar, +$baz) +{ +}; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/ValidDefaultValueStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/ValidDefaultValueStandard.xml new file mode 100644 index 0000000..56196cb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/ValidDefaultValueStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $persistent = false) +{ + ... +} + ]]> + + + $persistent = false, $dsn) +{ + ... +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidClassNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidClassNameStandard.xml new file mode 100644 index 0000000..d160879 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidClassNameStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidFunctionNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidFunctionNameStandard.xml new file mode 100644 index 0000000..60841dd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidFunctionNameStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidVariableNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidVariableNameStandard.xml new file mode 100644 index 0000000..4c707bd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidVariableNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + publicVar; + protected $protectedVar; + private $_privateVar; +} + ]]> + + + _publicVar; + protected $_protectedVar; + private $privateVar; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ObjectOperatorIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ObjectOperatorIndentStandard.xml new file mode 100644 index 0000000..9dee905 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ObjectOperatorIndentStandard.xml @@ -0,0 +1,39 @@ + + + + + + + ->bar() + ->baz(); + ]]> + + + -> + bar()-> + baz(); + ]]> + + + + + ->bar() + ->baz(); + ]]> + + + ->bar() +->baz(); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeClosingBraceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeClosingBraceStandard.xml new file mode 100644 index 0000000..c8d6e27 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeClosingBraceStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + } + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeIndentStandard.xml new file mode 100644 index 0000000..fafa07a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeIndentStandard.xml @@ -0,0 +1,29 @@ + + + + + + + if ($test) { + $var = 1; + } +} + ]]> + + + if ($test) { +$var = 1; +} +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Classes/ClassDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Classes/ClassDeclarationSniff.php new file mode 100644 index 0000000..893dc9a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Classes/ClassDeclarationSniff.php @@ -0,0 +1,150 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClassDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param integer $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $errorData = [strtolower($tokens[$stackPtr]['content'])]; + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $errorData); + return; + } + + $curlyBrace = $tokens[$stackPtr]['scope_opener']; + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($curlyBrace - 1), $stackPtr, true); + $classLine = $tokens[$lastContent]['line']; + $braceLine = $tokens[$curlyBrace]['line']; + if ($braceLine === $classLine) { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'same line'); + $error = 'Opening brace of a %s must be on the line after the definition'; + $fix = $phpcsFile->addFixableError($error, $curlyBrace, 'OpenBraceNewLine', $errorData); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + if ($tokens[($curlyBrace - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($curlyBrace - 1), ''); + } + + $phpcsFile->fixer->addNewlineBefore($curlyBrace); + $phpcsFile->fixer->endChangeset(); + } + + return; + } else { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'new line'); + + if ($braceLine > ($classLine + 1)) { + $error = 'Opening brace of a %s must be on the line following the %s declaration; found %s line(s)'; + $data = [ + $tokens[$stackPtr]['content'], + $tokens[$stackPtr]['content'], + ($braceLine - $classLine - 1), + ]; + $fix = $phpcsFile->addFixableError($error, $curlyBrace, 'OpenBraceWrongLine', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($curlyBrace - 1); $i > $lastContent; $i--) { + if ($tokens[$i]['line'] === ($tokens[$curlyBrace]['line'] + 1)) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + }//end if + }//end if + + if ($tokens[($curlyBrace + 1)]['content'] !== $phpcsFile->eolChar) { + $error = 'Opening %s brace must be on a line by itself'; + + $nextNonWhitespace = $phpcsFile->findNext(T_WHITESPACE, ($curlyBrace + 1), null, true); + if ($tokens[$nextNonWhitespace]['code'] === T_PHPCS_IGNORE) { + // Don't auto-fix if the next thing is a PHPCS ignore annotation. + $phpcsFile->addError($error, $curlyBrace, 'OpenBraceNotAlone', $errorData); + } else { + $fix = $phpcsFile->addFixableError($error, $curlyBrace, 'OpenBraceNotAlone', $errorData); + if ($fix === true) { + $phpcsFile->fixer->addNewline($curlyBrace); + } + } + } + + if ($tokens[($curlyBrace - 1)]['code'] === T_WHITESPACE) { + $prevContent = $tokens[($curlyBrace - 1)]['content']; + if ($prevContent === $phpcsFile->eolChar) { + $spaces = 0; + } else { + $spaces = $tokens[($curlyBrace - 1)]['length']; + } + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + $expected = ($tokens[$first]['column'] - 1); + if ($spaces !== $expected) { + $error = 'Expected %s spaces before opening brace; %s found'; + $data = [ + $expected, + $spaces, + ]; + + $fix = $phpcsFile->addFixableError($error, $curlyBrace, 'SpaceBeforeBrace', $data); + if ($fix === true) { + $indent = str_repeat(' ', $expected); + if ($spaces === 0) { + $phpcsFile->fixer->addContentBefore($curlyBrace, $indent); + } else { + $phpcsFile->fixer->replaceToken(($curlyBrace - 1), $indent); + } + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/ClassCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/ClassCommentSniff.php new file mode 100644 index 0000000..8fa6bfb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/ClassCommentSniff.php @@ -0,0 +1,122 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; + +class ClassCommentSniff extends FileCommentSniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $type = strtolower($tokens[$stackPtr]['content']); + $errorData = [$type]; + + $find = [ + T_ABSTRACT => T_ABSTRACT, + T_FINAL => T_FINAL, + T_READONLY => T_READONLY, + T_WHITESPACE => T_WHITESPACE, + ]; + + for ($commentEnd = ($stackPtr - 1); $commentEnd >= 0; $commentEnd--) { + if (isset($find[$tokens[$commentEnd]['code']]) === true) { + continue; + } + + if ($tokens[$commentEnd]['code'] === T_ATTRIBUTE_END + && isset($tokens[$commentEnd]['attribute_opener']) === true + ) { + $commentEnd = $tokens[$commentEnd]['attribute_opener']; + continue; + } + + break; + } + + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT + ) { + $errorData[] = $phpcsFile->getDeclarationName($stackPtr); + $phpcsFile->addError('Missing doc comment for %s %s', $stackPtr, 'Missing', $errorData); + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'no'); + return; + } + + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'yes'); + + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a %s comment', $stackPtr, 'WrongStyle', $errorData); + return; + } + + // Check each tag. + $this->processTags($phpcsFile, $stackPtr, $tokens[$commentEnd]['comment_opener']); + + }//end process() + + + /** + * Process the version tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processVersion($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if ((strstr($content, 'Release:') === false)) { + $error = 'Invalid version "%s" in doc comment; consider "Release: " instead'; + $data = [$content]; + $phpcsFile->addWarning($error, $tag, 'InvalidVersion', $data); + } + } + + }//end processVersion() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FileCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FileCommentSniff.php new file mode 100644 index 0000000..1c12e30 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FileCommentSniff.php @@ -0,0 +1,583 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class FileCommentSniff implements Sniff +{ + + /** + * Tags in correct order and related info. + * + * @var array + */ + protected $tags = [ + '@category' => [ + 'required' => true, + 'allow_multiple' => false, + ], + '@package' => [ + 'required' => true, + 'allow_multiple' => false, + ], + '@subpackage' => [ + 'required' => false, + 'allow_multiple' => false, + ], + '@author' => [ + 'required' => true, + 'allow_multiple' => true, + ], + '@copyright' => [ + 'required' => false, + 'allow_multiple' => true, + ], + '@license' => [ + 'required' => true, + 'allow_multiple' => false, + ], + '@version' => [ + 'required' => false, + 'allow_multiple' => false, + ], + '@link' => [ + 'required' => true, + 'allow_multiple' => true, + ], + '@see' => [ + 'required' => false, + 'allow_multiple' => true, + ], + '@since' => [ + 'required' => false, + 'allow_multiple' => false, + ], + '@deprecated' => [ + 'required' => false, + 'allow_multiple' => false, + ], + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int|void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Find the next non whitespace token. + $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + + // Allow declare() statements at the top of the file. + if ($tokens[$commentStart]['code'] === T_DECLARE) { + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($commentStart + 1)); + $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($semicolon + 1), null, true); + } + + // Ignore vim header. + if ($tokens[$commentStart]['code'] === T_COMMENT) { + if (strstr($tokens[$commentStart]['content'], 'vim:') !== false) { + $commentStart = $phpcsFile->findNext( + T_WHITESPACE, + ($commentStart + 1), + null, + true + ); + } + } + + $errorToken = ($stackPtr + 1); + if (isset($tokens[$errorToken]) === false) { + $errorToken--; + } + + if ($tokens[$commentStart]['code'] === T_CLOSE_TAG) { + // We are only interested if this is the first open tag. + return ($phpcsFile->numTokens + 1); + } else if ($tokens[$commentStart]['code'] === T_COMMENT) { + $error = 'You must use "/**" style comments for a file comment'; + $phpcsFile->addError($error, $errorToken, 'WrongStyle'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + return ($phpcsFile->numTokens + 1); + } else if ($commentStart === false + || $tokens[$commentStart]['code'] !== T_DOC_COMMENT_OPEN_TAG + ) { + $phpcsFile->addError('Missing file doc comment', $errorToken, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); + return ($phpcsFile->numTokens + 1); + } + + $commentEnd = $tokens[$commentStart]['comment_closer']; + + for ($nextToken = ($commentEnd + 1); $nextToken < $phpcsFile->numTokens; $nextToken++) { + if ($tokens[$nextToken]['code'] === T_WHITESPACE) { + continue; + } + + if ($tokens[$nextToken]['code'] === T_ATTRIBUTE + && isset($tokens[$nextToken]['attribute_closer']) === true + ) { + $nextToken = $tokens[$nextToken]['attribute_closer']; + continue; + } + + break; + } + + if ($nextToken === $phpcsFile->numTokens) { + $nextToken--; + } + + $ignore = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + T_CLOSURE, + T_PUBLIC, + T_PRIVATE, + T_PROTECTED, + T_FINAL, + T_STATIC, + T_ABSTRACT, + T_READONLY, + T_CONST, + T_PROPERTY, + ]; + + if (in_array($tokens[$nextToken]['code'], $ignore, true) === true) { + $phpcsFile->addError('Missing file doc comment', $stackPtr, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); + return ($phpcsFile->numTokens + 1); + } + + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + + // Check the PHP Version, which should be in some text before the first tag. + $found = false; + for ($i = ($commentStart + 1); $i < $commentEnd; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_TAG) { + break; + } else if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING + && strstr(strtolower($tokens[$i]['content']), 'php version') !== false + ) { + $found = true; + break; + } + } + + if ($found === false) { + $error = 'PHP version not specified'; + $phpcsFile->addWarning($error, $commentEnd, 'MissingVersion'); + } + + // Check each tag. + $this->processTags($phpcsFile, $stackPtr, $commentStart); + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + + /** + * Processes each required or optional tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart Position in the stack where the comment started. + * + * @return void + */ + protected function processTags($phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + if (get_class($this) === 'PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FileCommentSniff') { + $docBlock = 'file'; + } else { + $docBlock = 'class'; + } + + $commentEnd = $tokens[$commentStart]['comment_closer']; + + $foundTags = []; + $tagTokens = []; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + $name = $tokens[$tag]['content']; + if (isset($this->tags[$name]) === false) { + continue; + } + + if ($this->tags[$name]['allow_multiple'] === false && isset($tagTokens[$name]) === true) { + $error = 'Only one %s tag is allowed in a %s comment'; + $data = [ + $name, + $docBlock, + ]; + $phpcsFile->addError($error, $tag, 'Duplicate'.ucfirst(substr($name, 1)).'Tag', $data); + } + + $foundTags[] = $name; + $tagTokens[$name][] = $tag; + + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for %s tag in %s comment'; + $data = [ + $name, + $docBlock, + ]; + $phpcsFile->addError($error, $tag, 'Empty'.ucfirst(substr($name, 1)).'Tag', $data); + continue; + } + }//end foreach + + // Check if the tags are in the correct position. + $pos = 0; + foreach ($this->tags as $tag => $tagData) { + if (isset($tagTokens[$tag]) === false) { + if ($tagData['required'] === true) { + $error = 'Missing %s tag in %s comment'; + $data = [ + $tag, + $docBlock, + ]; + $phpcsFile->addError($error, $commentEnd, 'Missing'.ucfirst(substr($tag, 1)).'Tag', $data); + } + + continue; + } else { + $method = 'process'.substr($tag, 1); + if (method_exists($this, $method) === true) { + // Process each tag if a method is defined. + call_user_func([$this, $method], $phpcsFile, $tagTokens[$tag]); + } + } + + if (isset($foundTags[$pos]) === false) { + break; + } + + if ($foundTags[$pos] !== $tag) { + $error = 'The tag in position %s should be the %s tag'; + $data = [ + ($pos + 1), + $tag, + ]; + $phpcsFile->addError($error, $tokens[$commentStart]['comment_tags'][$pos], ucfirst(substr($tag, 1)).'TagOrder', $data); + } + + // Account for multiple tags. + $pos++; + while (isset($foundTags[$pos]) === true && $foundTags[$pos] === $tag) { + $pos++; + } + }//end foreach + + }//end processTags() + + + /** + * Process the category tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processCategory($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (Common::isUnderscoreName($content) !== true) { + $newContent = str_replace(' ', '_', $content); + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = ucfirst($firstBit).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= ucfirst($bit).'_'; + } + } + + $error = 'Category name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = [ + $content, + $validName, + ]; + $phpcsFile->addError($error, $tag, 'InvalidCategory', $data); + } + }//end foreach + + }//end processCategory() + + + /** + * Process the package tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processPackage($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (Common::isUnderscoreName($content) === true) { + continue; + } + + $newContent = str_replace(' ', '_', $content); + $newContent = trim($newContent, '_'); + $newContent = preg_replace('/[^A-Za-z_]/', '', $newContent); + + if ($newContent === '') { + $error = 'Package name "%s" is not valid'; + $data = [$content]; + $phpcsFile->addError($error, $tag, 'InvalidPackageValue', $data); + } else { + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = strtoupper($firstBit[0]).substr($firstBit, 1).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= strtoupper($bit[0]).substr($bit, 1).'_'; + } + } + + $error = 'Package name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = [ + $content, + $validName, + ]; + $phpcsFile->addError($error, $tag, 'InvalidPackage', $data); + }//end if + }//end foreach + + }//end processPackage() + + + /** + * Process the subpackage tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processSubpackage($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (Common::isUnderscoreName($content) === true) { + continue; + } + + $newContent = str_replace(' ', '_', $content); + $nameBits = explode('_', $newContent); + $firstBit = array_shift($nameBits); + $newName = strtoupper($firstBit[0]).substr($firstBit, 1).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= strtoupper($bit[0]).substr($bit, 1).'_'; + } + } + + $error = 'Subpackage name "%s" is not valid; consider "%s" instead'; + $validName = trim($newName, '_'); + $data = [ + $content, + $validName, + ]; + $phpcsFile->addError($error, $tag, 'InvalidSubpackage', $data); + }//end foreach + + }//end processSubpackage() + + + /** + * Process the author tag(s) that this header comment has. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processAuthor($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $local = '\da-zA-Z-_+'; + // Dot character cannot be the first or last character in the local-part. + $localMiddle = $local.'.\w'; + if (preg_match('/^([^<]*)\s+<(['.$local.'](['.$localMiddle.']*['.$local.'])*@[\da-zA-Z][-.\w]*[\da-zA-Z]\.[a-zA-Z]{2,})>$/', $content) === 0) { + $error = 'Content of the @author tag must be in the form "Display Name "'; + $phpcsFile->addError($error, $tag, 'InvalidAuthors'); + } + } + + }//end processAuthor() + + + /** + * Process the copyright tags. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processCopyright($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $matches = []; + if (preg_match('/^([0-9]{4})((.{1})([0-9]{4}))? (.+)$/', $content, $matches) !== 0) { + // Check earliest-latest year order. + if ($matches[3] !== '' && $matches[3] !== null) { + if ($matches[3] !== '-') { + $error = 'A hyphen must be used between the earliest and latest year'; + $phpcsFile->addError($error, $tag, 'CopyrightHyphen'); + } + + if ($matches[4] !== '' && $matches[4] !== null && $matches[4] < $matches[1]) { + $error = "Invalid year span \"$matches[1]$matches[3]$matches[4]\" found; consider \"$matches[4]-$matches[1]\" instead"; + $phpcsFile->addWarning($error, $tag, 'InvalidCopyright'); + } + } + } else { + $error = '@copyright tag must contain a year and the name of the copyright holder'; + $phpcsFile->addError($error, $tag, 'IncompleteCopyright'); + } + }//end foreach + + }//end processCopyright() + + + /** + * Process the license tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processLicense($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + $matches = []; + preg_match('/^([^\s]+)\s+(.*)/', $content, $matches); + if (count($matches) !== 3) { + $error = '@license tag must contain a URL and a license name'; + $phpcsFile->addError($error, $tag, 'IncompleteLicense'); + } + } + + }//end processLicense() + + + /** + * Process the version tag. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tags The tokens for these tags. + * + * @return void + */ + protected function processVersion($phpcsFile, array $tags) + { + $tokens = $phpcsFile->getTokens(); + foreach ($tags as $tag) { + if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { + // No content. + continue; + } + + $content = $tokens[($tag + 2)]['content']; + if (strstr($content, 'CVS:') === false + && strstr($content, 'SVN:') === false + && strstr($content, 'GIT:') === false + && strstr($content, 'HG:') === false + ) { + $error = 'Invalid version "%s" in file comment; consider "CVS: " or "SVN: " or "GIT: " or "HG: " instead'; + $data = [$content]; + $phpcsFile->addWarning($error, $tag, 'InvalidVersion', $data); + } + } + + }//end processVersion() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FunctionCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FunctionCommentSniff.php new file mode 100644 index 0000000..48ff5f2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FunctionCommentSniff.php @@ -0,0 +1,539 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionCommentSniff implements Sniff +{ + + /** + * Disable the check for functions with a lower visibility than the value given. + * + * Allowed values are public, protected, and private. + * + * @var string + */ + public $minimumVisibility = 'private'; + + /** + * Array of methods which do not require a return type. + * + * @var array + */ + public $specialMethods = [ + '__construct', + '__destruct', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $scopeModifier = $phpcsFile->getMethodProperties($stackPtr)['scope']; + if ($scopeModifier === 'protected' + && $this->minimumVisibility === 'public' + || $scopeModifier === 'private' + && ($this->minimumVisibility === 'public' || $this->minimumVisibility === 'protected') + ) { + return; + } + + $tokens = $phpcsFile->getTokens(); + $ignore = Tokens::$methodPrefixes; + $ignore[T_WHITESPACE] = T_WHITESPACE; + + for ($commentEnd = ($stackPtr - 1); $commentEnd >= 0; $commentEnd--) { + if (isset($ignore[$tokens[$commentEnd]['code']]) === true) { + continue; + } + + if ($tokens[$commentEnd]['code'] === T_ATTRIBUTE_END + && isset($tokens[$commentEnd]['attribute_opener']) === true + ) { + $commentEnd = $tokens[$commentEnd]['attribute_opener']; + continue; + } + + break; + } + + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + // Inline comments might just be closing comments for + // control structures or functions instead of function comments + // using the wrong comment type. If there is other code on the line, + // assume they relate to that code. + $prev = $phpcsFile->findPrevious($ignore, ($commentEnd - 1), null, true); + if ($prev !== false && $tokens[$prev]['line'] === $tokens[$commentEnd]['line']) { + $commentEnd = $prev; + } + } + + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT + ) { + $function = $phpcsFile->getDeclarationName($stackPtr); + $phpcsFile->addError( + 'Missing doc comment for function %s()', + $stackPtr, + 'Missing', + [$function] + ); + $phpcsFile->recordMetric($stackPtr, 'Function has doc comment', 'no'); + return; + } else { + $phpcsFile->recordMetric($stackPtr, 'Function has doc comment', 'yes'); + } + + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a function comment', $stackPtr, 'WrongStyle'); + return; + } + + if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) { + for ($i = ($commentEnd + 1); $i < $stackPtr; $i++) { + if ($tokens[$i]['column'] !== 1) { + continue; + } + + if ($tokens[$i]['code'] === T_WHITESPACE + && $tokens[$i]['line'] !== $tokens[($i + 1)]['line'] + ) { + $error = 'There must be no blank lines after the function comment'; + $fix = $phpcsFile->addFixableError($error, $commentEnd, 'SpacingAfter'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + while ($i < $stackPtr + && $tokens[$i]['code'] === T_WHITESPACE + && $tokens[$i]['line'] !== $tokens[($i + 1)]['line'] + ) { + $phpcsFile->fixer->replaceToken($i++, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + break; + } + }//end for + }//end if + + $commentStart = $tokens[$commentEnd]['comment_opener']; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@see') { + // Make sure the tag isn't empty. + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for @see tag in function comment'; + $phpcsFile->addError($error, $tag, 'EmptySees'); + } + } + } + + $this->processReturn($phpcsFile, $stackPtr, $commentStart); + $this->processThrows($phpcsFile, $stackPtr, $commentStart); + $this->processParams($phpcsFile, $stackPtr, $commentStart); + + }//end process() + + + /** + * Process the return comment of this function comment. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processReturn(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + // Skip constructor and destructor. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + $isSpecialMethod = in_array($methodName, $this->specialMethods, true); + + $return = null; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@return') { + if ($return !== null) { + $error = 'Only 1 @return tag is allowed in a function comment'; + $phpcsFile->addError($error, $tag, 'DuplicateReturn'); + return; + } + + $return = $tag; + } + } + + if ($return !== null) { + $content = $tokens[($return + 2)]['content']; + if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) { + $error = 'Return type missing for @return tag in function comment'; + $phpcsFile->addError($error, $return, 'MissingReturnType'); + } + } else { + if ($isSpecialMethod === true) { + return; + } + + $error = 'Missing @return tag in function comment'; + $phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn'); + }//end if + + }//end processReturn() + + + /** + * Process any throw tags that this function comment has. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processThrows(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] !== '@throws') { + continue; + } + + $exception = null; + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = []; + preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches); + $exception = $matches[1]; + } + + if ($exception === null) { + $error = 'Exception type missing for @throws tag in function comment'; + $phpcsFile->addError($error, $tag, 'InvalidThrows'); + } + }//end foreach + + }//end processThrows() + + + /** + * Process the function parameter comments. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processParams(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + $params = []; + $maxType = 0; + $maxVar = 0; + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($tokens[$tag]['content'] !== '@param') { + continue; + } + + $type = ''; + $typeSpace = 0; + $var = ''; + $varSpace = 0; + $comment = ''; + $commentEnd = 0; + $commentTokens = []; + + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = []; + preg_match('/((?:(?![$.]|&(?=\$)).)*)(?:((?:\.\.\.)?(?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches); + + if (empty($matches) === false) { + $typeLen = strlen($matches[1]); + $type = trim($matches[1]); + $typeSpace = ($typeLen - strlen($type)); + $typeLen = strlen($type); + if ($typeLen > $maxType) { + $maxType = $typeLen; + } + } + + if (isset($matches[2]) === true) { + $var = $matches[2]; + $varLen = strlen($var); + if ($varLen > $maxVar) { + $maxVar = $varLen; + } + + if (isset($matches[4]) === true) { + $varSpace = strlen($matches[3]); + $comment = $matches[4]; + + // Any strings until the next tag belong to this comment. + if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) { + $end = $tokens[$commentStart]['comment_tags'][($pos + 1)]; + } else { + $end = $tokens[$commentStart]['comment_closer']; + } + + for ($i = ($tag + 3); $i < $end; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) { + $comment .= ' '.$tokens[$i]['content']; + $commentEnd = $i; + $commentTokens[] = $i; + } + } + } else { + $error = 'Missing parameter comment'; + $phpcsFile->addError($error, $tag, 'MissingParamComment'); + }//end if + } else { + $error = 'Missing parameter name'; + $phpcsFile->addError($error, $tag, 'MissingParamName'); + }//end if + } else { + $error = 'Missing parameter type'; + $phpcsFile->addError($error, $tag, 'MissingParamType'); + }//end if + + $params[] = [ + 'tag' => $tag, + 'type' => $type, + 'var' => $var, + 'comment' => $comment, + 'comment_end' => $commentEnd, + 'comment_tokens' => $commentTokens, + 'type_space' => $typeSpace, + 'var_space' => $varSpace, + ]; + }//end foreach + + $realParams = $phpcsFile->getMethodParameters($stackPtr); + $foundParams = []; + + // We want to use ... for all variable length arguments, so add + // this prefix to the variable name so comparisons are easier. + foreach ($realParams as $pos => $param) { + if ($param['variable_length'] === true) { + $realParams[$pos]['name'] = '...'.$realParams[$pos]['name']; + } + } + + foreach ($params as $pos => $param) { + if ($param['var'] === '') { + continue; + } + + $foundParams[] = $param['var']; + + if (trim($param['type']) !== '') { + // Check number of spaces after the type. + $spaces = ($maxType - strlen($param['type']) + 1); + if ($param['type_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter type; %s found'; + $data = [ + $spaces, + $param['type_space'], + ]; + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data); + if ($fix === true) { + $commentToken = ($param['tag'] + 2); + + $content = $param['type']; + $content .= str_repeat(' ', $spaces); + $content .= $param['var']; + $content .= str_repeat(' ', $param['var_space']); + + $wrapLength = ($tokens[$commentToken]['length'] - $param['type_space'] - $param['var_space'] - strlen($param['type']) - strlen($param['var'])); + + $star = $phpcsFile->findPrevious(T_DOC_COMMENT_STAR, $param['tag']); + $spaceLength = (strlen($content) + $tokens[($commentToken - 1)]['length'] + $tokens[($commentToken - 2)]['length']); + + $padding = str_repeat(' ', ($tokens[$star]['column'] - 1)); + $padding .= '* '; + $padding .= str_repeat(' ', $spaceLength); + + $content .= wordwrap( + $param['comment'], + $wrapLength, + $phpcsFile->eolChar.$padding + ); + + $phpcsFile->fixer->replaceToken($commentToken, $content); + for ($i = ($commentToken + 1); $i <= $param['comment_end']; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + }//end if + }//end if + }//end if + + // Make sure the param name is correct. + if (isset($realParams[$pos]) === true) { + $realName = $realParams[$pos]['name']; + if ($realName !== $param['var']) { + $code = 'ParamNameNoMatch'; + $data = [ + $param['var'], + $realName, + ]; + + $error = 'Doc comment for parameter %s does not match '; + if (strtolower($param['var']) === strtolower($realName)) { + $error .= 'case of '; + $code = 'ParamNameNoCaseMatch'; + } + + $error .= 'actual variable name %s'; + + $phpcsFile->addError($error, $param['tag'], $code, $data); + } + } else if (substr($param['var'], -4) !== ',...') { + // We must have an extra parameter comment. + $error = 'Superfluous parameter comment'; + $phpcsFile->addError($error, $param['tag'], 'ExtraParamComment'); + }//end if + + if ($param['comment'] === '') { + continue; + } + + // Check number of spaces after the param name. + $spaces = ($maxVar - strlen($param['var']) + 1); + if ($param['var_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter name; %s found'; + $data = [ + $spaces, + $param['var_space'], + ]; + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamName', $data); + if ($fix === true) { + $commentToken = ($param['tag'] + 2); + + $content = $param['type']; + $content .= str_repeat(' ', $param['type_space']); + $content .= $param['var']; + $content .= str_repeat(' ', $spaces); + + $wrapLength = ($tokens[$commentToken]['length'] - $param['type_space'] - $param['var_space'] - strlen($param['type']) - strlen($param['var'])); + + $star = $phpcsFile->findPrevious(T_DOC_COMMENT_STAR, $param['tag']); + $spaceLength = (strlen($content) + $tokens[($commentToken - 1)]['length'] + $tokens[($commentToken - 2)]['length']); + + $padding = str_repeat(' ', ($tokens[$star]['column'] - 1)); + $padding .= '* '; + $padding .= str_repeat(' ', $spaceLength); + + $content .= wordwrap( + $param['comment'], + $wrapLength, + $phpcsFile->eolChar.$padding + ); + + $phpcsFile->fixer->replaceToken($commentToken, $content); + for ($i = ($commentToken + 1); $i <= $param['comment_end']; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + }//end if + }//end if + + // Check the alignment of multi-line param comments. + if ($param['tag'] !== $param['comment_end']) { + $wrapLength = ($tokens[($param['tag'] + 2)]['length'] - $param['type_space'] - $param['var_space'] - strlen($param['type']) - strlen($param['var'])); + + $startColumn = ($tokens[($param['tag'] + 2)]['column'] + $tokens[($param['tag'] + 2)]['length'] - $wrapLength); + + $star = $phpcsFile->findPrevious(T_DOC_COMMENT_STAR, $param['tag']); + $expected = ($startColumn - $tokens[$star]['column'] - 1); + + foreach ($param['comment_tokens'] as $commentToken) { + if ($tokens[$commentToken]['column'] === $startColumn) { + continue; + } + + $found = 0; + if ($tokens[($commentToken - 1)]['code'] === T_DOC_COMMENT_WHITESPACE) { + $found = $tokens[($commentToken - 1)]['length']; + } + + $error = 'Parameter comment not aligned correctly; expected %s spaces but found %s'; + $data = [ + $expected, + $found, + ]; + + if ($found < $expected) { + $code = 'ParamCommentAlignment'; + } else { + $code = 'ParamCommentAlignmentExceeded'; + } + + $fix = $phpcsFile->addFixableError($error, $commentToken, $code, $data); + if ($fix === true) { + $padding = str_repeat(' ', $expected); + if ($tokens[($commentToken - 1)]['code'] === T_DOC_COMMENT_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($commentToken - 1), $padding); + } else { + $phpcsFile->fixer->addContentBefore($commentToken, $padding); + } + } + }//end foreach + }//end if + }//end foreach + + $realNames = []; + foreach ($realParams as $realParam) { + $realNames[] = $realParam['name']; + } + + // Report missing comments. + $diff = array_diff($realNames, $foundParams); + foreach ($diff as $neededParam) { + $error = 'Doc comment for parameter "%s" missing'; + $data = [$neededParam]; + $phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data); + } + + }//end processParams() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/InlineCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/InlineCommentSniff.php new file mode 100644 index 0000000..71c1180 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/InlineCommentSniff.php @@ -0,0 +1,68 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class InlineCommentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_COMMENT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['content'][0] === '#') { + $phpcsFile->recordMetric($stackPtr, 'Inline comment style', '# ...'); + + $error = 'Perl-style comments are not allowed. Use "// Comment."'; + $error .= ' or "/* comment */" instead.'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'WrongStyle'); + if ($fix === true) { + $newComment = ltrim($tokens[$stackPtr]['content'], '# '); + $newComment = '// '.$newComment; + $phpcsFile->fixer->replaceToken($stackPtr, $newComment); + } + } else if ($tokens[$stackPtr]['content'][0] === '/' + && $tokens[$stackPtr]['content'][1] === '/' + ) { + $phpcsFile->recordMetric($stackPtr, 'Inline comment style', '// ...'); + } else if ($tokens[$stackPtr]['content'][0] === '/' + && $tokens[$stackPtr]['content'][1] === '*' + ) { + $phpcsFile->recordMetric($stackPtr, 'Inline comment style', '/* ... */'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/ControlSignatureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/ControlSignatureSniff.php new file mode 100644 index 0000000..4ca5451 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/ControlSignatureSniff.php @@ -0,0 +1,48 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Sniffs\AbstractPatternSniff; + +class ControlSignatureSniff extends AbstractPatternSniff +{ + + /** + * If true, comments will be ignored if they are found in the code. + * + * @var boolean + */ + public $ignoreComments = true; + + + /** + * Returns the patterns that this test wishes to verify. + * + * @return string[] + */ + protected function getPatterns() + { + return [ + 'do {EOL...} while (...);EOL', + 'while (...) {EOL', + 'for (...) {EOL', + 'if (...) {EOL', + 'foreach (...) {EOL', + '} else if (...) {EOL', + '} elseif (...) {EOL', + '} else {EOL', + 'do {EOL', + 'match (...) {EOL', + ]; + + }//end getPatterns() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/MultiLineConditionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/MultiLineConditionSniff.php new file mode 100644 index 0000000..08752ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/MultiLineConditionSniff.php @@ -0,0 +1,283 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class MultiLineConditionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_ELSEIF, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false) { + return; + } + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + $spaceAfterOpen = 0; + if ($tokens[($openBracket + 1)]['code'] === T_WHITESPACE) { + if (strpos($tokens[($openBracket + 1)]['content'], $phpcsFile->eolChar) !== false) { + $spaceAfterOpen = 'newline'; + } else { + $spaceAfterOpen = $tokens[($openBracket + 1)]['length']; + } + } + + if ($spaceAfterOpen !== 0) { + $error = 'First condition of a multi-line IF statement must directly follow the opening parenthesis'; + $fix = $phpcsFile->addFixableError($error, ($openBracket + 1), 'SpacingAfterOpenBrace'); + if ($fix === true) { + if ($spaceAfterOpen === 'newline') { + $phpcsFile->fixer->replaceToken(($openBracket + 1), ''); + } else { + $phpcsFile->fixer->replaceToken(($openBracket + 1), ''); + } + } + } + + // We need to work out how far indented the if statement + // itself is, so we can work out how far to indent conditions. + $statementIndent = 0; + for ($i = ($stackPtr - 1); $i >= 0; $i--) { + if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) { + $i++; + break; + } + } + + if ($i >= 0 && $tokens[$i]['code'] === T_WHITESPACE) { + $statementIndent = $tokens[$i]['length']; + } + + // Each line between the parenthesis should be indented 4 spaces + // and start with an operator, unless the line is inside a + // function call, in which case it is ignored. + $prevLine = $tokens[$openBracket]['line']; + for ($i = ($openBracket + 1); $i <= $closeBracket; $i++) { + if ($i === $closeBracket && $tokens[$openBracket]['line'] !== $tokens[$i]['line']) { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), null, true); + if ($tokens[$prev]['line'] === $tokens[$i]['line']) { + // Closing bracket is on the same line as a condition. + $error = 'Closing parenthesis of a multi-line IF statement must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'CloseBracketNewLine'); + if ($fix === true) { + // Account for a comment at the end of the line. + $next = $phpcsFile->findNext(T_WHITESPACE, ($closeBracket + 1), null, true); + if ($tokens[$next]['code'] !== T_COMMENT + && isset(Tokens::$phpcsCommentTokens[$tokens[$next]['code']]) === false + ) { + $phpcsFile->fixer->addNewlineBefore($closeBracket); + } else { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($closeBracket, ''); + $phpcsFile->fixer->addContentBefore($next, ')'); + $phpcsFile->fixer->endChangeset(); + } + } + } + }//end if + + if ($tokens[$i]['line'] !== $prevLine) { + if ($tokens[$i]['line'] === $tokens[$closeBracket]['line']) { + $next = $phpcsFile->findNext(T_WHITESPACE, $i, null, true); + if ($next !== $closeBracket) { + $expectedIndent = ($statementIndent + $this->indent); + } else { + // Closing brace needs to be indented to the same level + // as the statement. + $expectedIndent = $statementIndent; + }//end if + } else { + $expectedIndent = ($statementIndent + $this->indent); + }//end if + + if ($tokens[$i]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$i]['code']]) === true + ) { + $prevLine = $tokens[$i]['line']; + continue; + } + + // We changed lines, so this should be a whitespace indent token. + if ($tokens[$i]['code'] !== T_WHITESPACE) { + $foundIndent = 0; + } else { + $foundIndent = $tokens[$i]['length']; + } + + if ($expectedIndent !== $foundIndent) { + $error = 'Multi-line IF statement not indented correctly; expected %s spaces but found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $i, 'Alignment', $data); + if ($fix === true) { + $spaces = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($i, $spaces); + } else { + $phpcsFile->fixer->replaceToken($i, $spaces); + } + } + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $i, null, true); + if ($next !== $closeBracket && $tokens[$next]['line'] === $tokens[$i]['line']) { + if (isset(Tokens::$booleanOperators[$tokens[$next]['code']]) === false) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), $openBracket, true); + $fixable = true; + if (isset(Tokens::$booleanOperators[$tokens[$prev]['code']]) === false + && $phpcsFile->findNext(T_WHITESPACE, ($prev + 1), $next, true) !== false + ) { + // Condition spread over multi-lines interspersed with comments. + $fixable = false; + } + + $error = 'Each line in a multi-line IF statement must begin with a boolean operator'; + if ($fixable === false) { + $phpcsFile->addError($error, $next, 'StartWithBoolean'); + } else { + $fix = $phpcsFile->addFixableError($error, $next, 'StartWithBoolean'); + if ($fix === true) { + if (isset(Tokens::$booleanOperators[$tokens[$prev]['code']]) === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($prev, ''); + $phpcsFile->fixer->addContentBefore($next, $tokens[$prev]['content'].' '); + $phpcsFile->fixer->endChangeset(); + } else { + for ($x = ($prev + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + } + } + } + }//end if + }//end if + + $prevLine = $tokens[$i]['line']; + }//end if + + if ($tokens[$i]['code'] === T_STRING) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true); + if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { + // This is a function call, so skip to the end as they + // have their own indentation rules. + $i = $tokens[$next]['parenthesis_closer']; + $prevLine = $tokens[$i]['line']; + continue; + } + } + }//end for + + // From here on, we are checking the spacing of the opening and closing + // braces. If this IF statement does not use braces, we end here. + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + // The opening brace needs to be one space away from the closing parenthesis. + $openBrace = $tokens[$stackPtr]['scope_opener']; + $next = $phpcsFile->findNext(T_WHITESPACE, ($closeBracket + 1), $openBrace, true); + if ($next !== false) { + // Probably comments in between tokens, so don't check. + return; + } + + if ($tokens[$openBrace]['line'] > $tokens[$closeBracket]['line']) { + $length = -1; + } else if ($openBrace === ($closeBracket + 1)) { + $length = 0; + } else if ($openBrace === ($closeBracket + 2) + && $tokens[($closeBracket + 1)]['code'] === T_WHITESPACE + ) { + $length = $tokens[($closeBracket + 1)]['length']; + } else { + // Confused, so don't check. + $length = 1; + } + + if ($length === 1) { + return; + } + + $data = [$length]; + $code = 'SpaceBeforeOpenBrace'; + + $error = 'There must be a single space between the closing parenthesis and the opening brace of a multi-line IF statement; found '; + if ($length === -1) { + $error .= 'newline'; + $code = 'NewlineBeforeOpenBrace'; + } else { + $error .= '%s spaces'; + } + + $fix = $phpcsFile->addFixableError($error, ($closeBracket + 1), $code, $data); + if ($fix === true) { + if ($length === 0) { + $phpcsFile->fixer->addContent($closeBracket, ' '); + } else { + $phpcsFile->fixer->replaceToken(($closeBracket + 1), ' '); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Files/IncludingFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Files/IncludingFileSniff.php new file mode 100644 index 0000000..e0ed0fb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Files/IncludingFileSniff.php @@ -0,0 +1,136 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class IncludingFileSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_INCLUDE_ONCE, + T_REQUIRE_ONCE, + T_REQUIRE, + T_INCLUDE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($tokens[$nextToken]['code'] === T_OPEN_PARENTHESIS) { + $error = '"%s" is a statement not a function; no parentheses are required'; + $data = [$tokens[$stackPtr]['content']]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'BracketsNotRequired', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($tokens[$nextToken]['parenthesis_closer'], ''); + if ($tokens[($nextToken - 1)]['code'] !== T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($nextToken, ' '); + } else { + $phpcsFile->fixer->replaceToken($nextToken, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + if (count($tokens[$stackPtr]['conditions']) !== 0) { + $inCondition = true; + } else { + $inCondition = false; + } + + // Check to see if this including statement is within the parenthesis + // of a condition. If that's the case then we need to process it as being + // within a condition, as they are checking the return value. + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $left => $right) { + if (isset($tokens[$left]['parenthesis_owner']) === true) { + $inCondition = true; + } + } + } + + // Check to see if they are assigning the return value of this + // including call. If they are then they are probably checking it, so + // it's conditional. + $previous = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if (isset(Tokens::$assignmentTokens[$tokens[$previous]['code']]) === true) { + // The have assigned the return value to it, so its conditional. + $inCondition = true; + } + + $tokenCode = $tokens[$stackPtr]['code']; + if ($inCondition === true) { + // We are inside a conditional statement. We need an include_once. + if ($tokenCode === T_REQUIRE_ONCE) { + $error = 'File is being conditionally included; '; + $error .= 'use "include_once" instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'UseIncludeOnce'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'include_once'); + } + } else if ($tokenCode === T_REQUIRE) { + $error = 'File is being conditionally included; '; + $error .= 'use "include" instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'UseInclude'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'include'); + } + } + } else { + // We are unconditionally including, we need a require_once. + if ($tokenCode === T_INCLUDE_ONCE) { + $error = 'File is being unconditionally included; '; + $error .= 'use "require_once" instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'UseRequireOnce'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'require_once'); + } + } else if ($tokenCode === T_INCLUDE) { + $error = 'File is being unconditionally included; '; + $error .= 'use "require" instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'UseRequire'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'require'); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Formatting/MultiLineAssignmentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Formatting/MultiLineAssignmentSniff.php new file mode 100644 index 0000000..0f18710 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Formatting/MultiLineAssignmentSniff.php @@ -0,0 +1,106 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class MultiLineAssignmentSniff implements Sniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_EQUAL]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Equal sign can't be the last thing on the line. + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($next === false) { + // Bad assignment. + return; + } + + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + $error = 'Multi-line assignments must have the equal sign on the second line'; + $phpcsFile->addError($error, $stackPtr, 'EqualSignLine'); + return; + } + + // Make sure it is the first thing on the line, otherwise we ignore it. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), false, true); + if ($prev === false) { + // Bad assignment. + return; + } + + if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']) { + return; + } + + // Find the required indent based on the ident of the previous line. + $assignmentIndent = 0; + $prevLine = $tokens[$prev]['line']; + for ($i = ($prev - 1); $i >= 0; $i--) { + if ($tokens[$i]['line'] !== $prevLine) { + $i++; + break; + } + } + + if ($tokens[$i]['code'] === T_WHITESPACE) { + $assignmentIndent = $tokens[$i]['length']; + } + + // Find the actual indent. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1)); + + $expectedIndent = ($assignmentIndent + $this->indent); + $foundIndent = $tokens[$prev]['length']; + if ($foundIndent !== $expectedIndent) { + $error = 'Multi-line assignment not indented correctly; expected %s spaces but found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + $phpcsFile->addError($error, $stackPtr, 'Indent', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionCallSignatureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionCallSignatureSniff.php new file mode 100644 index 0000000..772ab6b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionCallSignatureSniff.php @@ -0,0 +1,634 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionCallSignatureSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + /** + * If TRUE, multiple arguments can be defined per line in a multi-line call. + * + * @var boolean + */ + public $allowMultipleArguments = true; + + /** + * How many spaces should follow the opening bracket. + * + * @var integer + */ + public $requiredSpacesAfterOpen = 0; + + /** + * How many spaces should precede the closing bracket. + * + * @var integer + */ + public $requiredSpacesBeforeClose = 0; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $tokens = Tokens::$functionNameTokens; + + $tokens[] = T_VARIABLE; + $tokens[] = T_CLOSE_CURLY_BRACKET; + $tokens[] = T_CLOSE_SQUARE_BRACKET; + $tokens[] = T_CLOSE_PARENTHESIS; + + return $tokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $this->requiredSpacesAfterOpen = (int) $this->requiredSpacesAfterOpen; + $this->requiredSpacesBeforeClose = (int) $this->requiredSpacesBeforeClose; + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_CLOSE_CURLY_BRACKET + && isset($tokens[$stackPtr]['scope_condition']) === true + ) { + // Not a function call. + return; + } + + // Find the next non-empty token. + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + + if ($tokens[$openBracket]['code'] !== T_OPEN_PARENTHESIS) { + // Not a function call. + return; + } + + if (isset($tokens[$openBracket]['parenthesis_closer']) === false) { + // Not a function call. + return; + } + + // Find the previous non-empty token. + $search = Tokens::$emptyTokens; + $search[] = T_BITWISE_AND; + $previous = $phpcsFile->findPrevious($search, ($stackPtr - 1), null, true); + if ($tokens[$previous]['code'] === T_FUNCTION) { + // It's a function definition, not a function call. + return; + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + if (($stackPtr + 1) !== $openBracket) { + // Checking this: $value = my_function[*](...). + $error = 'Space before opening parenthesis of function call prohibited'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeOpenBracket'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($stackPtr + 1); $i < $openBracket; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + // Modify the bracket as well to ensure a conflict if the bracket + // has been changed in some way by another sniff. + $phpcsFile->fixer->replaceToken($openBracket, '('); + $phpcsFile->fixer->endChangeset(); + } + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($closeBracket + 1), null, true); + if ($tokens[$next]['code'] === T_SEMICOLON) { + if (isset(Tokens::$emptyTokens[$tokens[($closeBracket + 1)]['code']]) === true) { + $error = 'Space after closing parenthesis of function call prohibited'; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'SpaceAfterCloseBracket'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($closeBracket + 1); $i < $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + // Modify the bracket as well to ensure a conflict if the bracket + // has been changed in some way by another sniff. + $phpcsFile->fixer->replaceToken($closeBracket, ')'); + $phpcsFile->fixer->endChangeset(); + } + } + } + + // Check if this is a single line or multi-line function call. + if ($this->isMultiLineCall($phpcsFile, $stackPtr, $openBracket, $tokens) === true) { + $this->processMultiLineCall($phpcsFile, $stackPtr, $openBracket, $tokens); + } else { + $this->processSingleLineCall($phpcsFile, $stackPtr, $openBracket, $tokens); + } + + }//end process() + + + /** + * Determine if this is a multi-line function call. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return bool + */ + public function isMultiLineCall(File $phpcsFile, $stackPtr, $openBracket, $tokens) + { + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + if ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']) { + return true; + } + + return false; + + }//end isMultiLineCall() + + + /** + * Processes single-line calls. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processSingleLineCall(File $phpcsFile, $stackPtr, $openBracket, $tokens) + { + $closer = $tokens[$openBracket]['parenthesis_closer']; + if ($openBracket === ($closer - 1)) { + return; + } + + // If the function call has no arguments or comments, enforce 0 spaces. + $next = $phpcsFile->findNext(T_WHITESPACE, ($openBracket + 1), $closer, true); + if ($next === false) { + $requiredSpacesAfterOpen = 0; + $requiredSpacesBeforeClose = 0; + } else { + $requiredSpacesAfterOpen = $this->requiredSpacesAfterOpen; + $requiredSpacesBeforeClose = $this->requiredSpacesBeforeClose; + } + + if ($requiredSpacesAfterOpen === 0 && $tokens[($openBracket + 1)]['code'] === T_WHITESPACE) { + // Checking this: $value = my_function([*]...). + $error = 'Space after opening parenthesis of function call prohibited'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterOpenBracket'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($openBracket + 1), ''); + } + } else if ($requiredSpacesAfterOpen > 0) { + $spaceAfterOpen = 0; + if ($tokens[($openBracket + 1)]['code'] === T_WHITESPACE) { + $spaceAfterOpen = $tokens[($openBracket + 1)]['length']; + } + + if ($spaceAfterOpen !== $requiredSpacesAfterOpen) { + $error = 'Expected %s spaces after opening parenthesis; %s found'; + $data = [ + $requiredSpacesAfterOpen, + $spaceAfterOpen, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterOpenBracket', $data); + if ($fix === true) { + $padding = str_repeat(' ', $requiredSpacesAfterOpen); + if ($spaceAfterOpen === 0) { + $phpcsFile->fixer->addContent($openBracket, $padding); + } else { + $phpcsFile->fixer->replaceToken(($openBracket + 1), $padding); + } + } + } + }//end if + + // Checking this: $value = my_function(...[*]). + $spaceBeforeClose = 0; + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($closer - 1), $openBracket, true); + if ($tokens[$prev]['code'] === T_END_HEREDOC || $tokens[$prev]['code'] === T_END_NOWDOC) { + // Need a newline after these tokens, so ignore this rule. + return; + } + + if ($tokens[$prev]['line'] !== $tokens[$closer]['line']) { + $spaceBeforeClose = 'newline'; + } else if ($tokens[($closer - 1)]['code'] === T_WHITESPACE) { + $spaceBeforeClose = $tokens[($closer - 1)]['length']; + } + + if ($spaceBeforeClose !== $requiredSpacesBeforeClose) { + $error = 'Expected %s spaces before closing parenthesis; %s found'; + $data = [ + $requiredSpacesBeforeClose, + $spaceBeforeClose, + ]; + $fix = $phpcsFile->addFixableError($error, $closer, 'SpaceBeforeCloseBracket', $data); + if ($fix === true) { + $padding = str_repeat(' ', $requiredSpacesBeforeClose); + + if ($spaceBeforeClose === 0) { + $phpcsFile->fixer->addContentBefore($closer, $padding); + } else if ($spaceBeforeClose === 'newline') { + $phpcsFile->fixer->beginChangeset(); + + $closingContent = ')'; + + $next = $phpcsFile->findNext(T_WHITESPACE, ($closer + 1), null, true); + if ($tokens[$next]['code'] === T_SEMICOLON) { + $closingContent .= ';'; + for ($i = ($closer + 1); $i <= $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + + // We want to jump over any whitespace or inline comment and + // move the closing parenthesis after any other token. + $prev = ($closer - 1); + while (isset(Tokens::$emptyTokens[$tokens[$prev]['code']]) === true) { + if (($tokens[$prev]['code'] === T_COMMENT) + && (strpos($tokens[$prev]['content'], '*/') !== false) + ) { + break; + } + + $prev--; + } + + $phpcsFile->fixer->addContent($prev, $padding.$closingContent); + + $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($closer - 1), null, true); + for ($i = ($prevNonWhitespace + 1); $i <= $closer; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($closer - 1), $padding); + }//end if + }//end if + }//end if + + }//end processSingleLineCall() + + + /** + * Processes multi-line calls. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processMultiLineCall(File $phpcsFile, $stackPtr, $openBracket, $tokens) + { + // We need to work out how far indented the function + // call itself is, so we can work out how far to + // indent the arguments. + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + if ($first !== false + && $tokens[$first]['code'] === T_CONSTANT_ENCAPSED_STRING + && $tokens[($first - 1)]['code'] === T_CONSTANT_ENCAPSED_STRING + ) { + // We are in a multi-line string, so find the start and use + // the indent from there. + $prev = $phpcsFile->findPrevious(T_CONSTANT_ENCAPSED_STRING, ($first - 2), null, true); + $first = $phpcsFile->findFirstOnLine(Tokens::$emptyTokens, $prev, true); + if ($first === false) { + $first = ($prev + 1); + } + } + + $foundFunctionIndent = 0; + if ($first !== false) { + if ($tokens[$first]['code'] === T_INLINE_HTML + || ($tokens[$first]['code'] === T_CONSTANT_ENCAPSED_STRING + && $tokens[($first - 1)]['code'] === T_CONSTANT_ENCAPSED_STRING) + ) { + $trimmed = ltrim($tokens[$first]['content']); + if ($trimmed === '') { + $foundFunctionIndent = strlen($tokens[$first]['content']); + } else { + $foundFunctionIndent = (strlen($tokens[$first]['content']) - strlen($trimmed)); + } + } else { + $foundFunctionIndent = ($tokens[$first]['column'] - 1); + } + } + + // Make sure the function indent is divisible by the indent size. + // We round down here because this accounts for times when the + // surrounding code is indented a little too far in, and not correctly + // at a tab stop. Without this, the function will be indented a further + // $indent spaces to the right. + $functionIndent = (int) (floor($foundFunctionIndent / $this->indent) * $this->indent); + $adjustment = 0; + + if ($foundFunctionIndent !== $functionIndent) { + $error = 'Opening statement of multi-line function call not indented correctly; expected %s spaces but found %s'; + $data = [ + $functionIndent, + $foundFunctionIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $first, 'OpeningIndent', $data); + if ($fix === true) { + // Set adjustment for use later to determine whether argument indentation is correct when fixing. + $adjustment = ($functionIndent - $foundFunctionIndent); + + $padding = str_repeat(' ', $functionIndent); + if ($foundFunctionIndent === 0) { + $phpcsFile->fixer->addContentBefore($first, $padding); + } else if ($tokens[$first]['code'] === T_INLINE_HTML) { + $newContent = $padding.ltrim($tokens[$first]['content']); + $phpcsFile->fixer->replaceToken($first, $newContent); + } else { + $phpcsFile->fixer->replaceToken(($first - 1), $padding); + } + } + }//end if + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$openBracket]['line']) { + $error = 'Opening parenthesis of a multi-line function call must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentAfterOpenBracket'); + if ($fix === true) { + $phpcsFile->fixer->addContent( + $openBracket, + $phpcsFile->eolChar.str_repeat(' ', ($foundFunctionIndent + $this->indent)) + ); + } + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBracket - 1), null, true); + if ($tokens[$prev]['line'] === $tokens[$closeBracket]['line']) { + $error = 'Closing parenthesis of a multi-line function call must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'CloseBracketLine'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore( + $closeBracket, + $phpcsFile->eolChar.str_repeat(' ', ($foundFunctionIndent + $this->indent)) + ); + } + } + + // Each line between the parenthesis should be indented n spaces. + $lastLine = ($tokens[$openBracket]['line'] - 1); + $argStart = null; + $argEnd = null; + + // Start processing at the first argument. + $i = $phpcsFile->findNext(T_WHITESPACE, ($openBracket + 1), null, true); + + if ($tokens[$i]['line'] > ($tokens[$openBracket]['line'] + 1)) { + $error = 'The first argument in a multi-line function call must be on the line after the opening parenthesis'; + $fix = $phpcsFile->addFixableError($error, $i, 'FirstArgumentPosition'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($openBracket + 1); $x < $i; $x++) { + if ($tokens[$x]['line'] === $tokens[$openBracket]['line']) { + continue; + } + + if ($tokens[$x]['line'] === $tokens[$i]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + $i = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); + + if ($tokens[($i - 1)]['code'] === T_WHITESPACE + && $tokens[($i - 1)]['line'] === $tokens[$i]['line'] + ) { + // Make sure we check the indent. + $i--; + } + + for ($i; $i < $closeBracket; $i++) { + if ($i > $argStart && $i < $argEnd) { + $inArg = true; + } else { + $inArg = false; + } + + if ($tokens[$i]['line'] !== $lastLine) { + $lastLine = $tokens[$i]['line']; + + // Ignore heredoc indentation. + if (isset(Tokens::$heredocTokens[$tokens[$i]['code']]) === true) { + continue; + } + + // Ignore multi-line string indentation. + if (isset(Tokens::$stringTokens[$tokens[$i]['code']]) === true + && $tokens[$i]['code'] === $tokens[($i - 1)]['code'] + ) { + continue; + } + + // Ignore inline HTML. + if ($tokens[$i]['code'] === T_INLINE_HTML) { + continue; + } + + if ($tokens[$i]['line'] !== $tokens[$openBracket]['line']) { + // We changed lines, so this should be a whitespace indent token, but first make + // sure it isn't a blank line because we don't need to check indent unless there + // is actually some code to indent. + if ($tokens[$i]['code'] === T_WHITESPACE) { + $nextCode = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), ($closeBracket + 1), true); + if ($tokens[$nextCode]['line'] !== $lastLine) { + if ($inArg === false) { + $error = 'Empty lines are not allowed in multi-line function calls'; + $fix = $phpcsFile->addFixableError($error, $i, 'EmptyLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + + continue; + } + } else { + $nextCode = $i; + } + + if ($tokens[$nextCode]['line'] === $tokens[$closeBracket]['line']) { + // Closing brace needs to be indented to the same level + // as the function call. + $inArg = false; + $expectedIndent = ($foundFunctionIndent + $adjustment); + } else { + $expectedIndent = ($foundFunctionIndent + $this->indent + $adjustment); + } + + if ($tokens[$i]['code'] !== T_WHITESPACE + && $tokens[$i]['code'] !== T_DOC_COMMENT_WHITESPACE + ) { + // Just check if it is a multi-line block comment. If so, we can + // calculate the indent from the whitespace before the content. + if ($tokens[$i]['code'] === T_COMMENT + && $tokens[($i - 1)]['code'] === T_COMMENT + ) { + $trimmedLength = strlen(ltrim($tokens[$i]['content'])); + if ($trimmedLength === 0) { + // This is a blank comment line, so indenting it is + // pointless. + continue; + } + + $foundIndent = (strlen($tokens[$i]['content']) - $trimmedLength); + } else { + $foundIndent = 0; + } + } else { + $foundIndent = $tokens[$i]['length']; + } + + if ($foundIndent < $expectedIndent + || ($inArg === false + && $expectedIndent !== $foundIndent) + ) { + $error = 'Multi-line function call not indented correctly; expected %s spaces but found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $i, 'Indent', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + $padding = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($i, $padding); + if (isset($tokens[$i]['scope_opener']) === true) { + $phpcsFile->fixer->changeCodeBlockIndent($i, $tokens[$i]['scope_closer'], $expectedIndent); + } + } else { + if ($tokens[$i]['code'] === T_COMMENT) { + $comment = $padding.ltrim($tokens[$i]['content']); + $phpcsFile->fixer->replaceToken($i, $comment); + } else { + $phpcsFile->fixer->replaceToken($i, $padding); + } + + if (isset($tokens[($i + 1)]['scope_opener']) === true) { + $phpcsFile->fixer->changeCodeBlockIndent(($i + 1), $tokens[($i + 1)]['scope_closer'], ($expectedIndent - $foundIndent)); + } + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + } else { + $nextCode = $i; + }//end if + + if ($inArg === false) { + $argStart = $nextCode; + $argEnd = $phpcsFile->findEndOfStatement($nextCode, [T_COLON]); + } + }//end if + + // If we are within an argument we should be ignoring commas + // as these are not signalling the end of an argument. + if ($inArg === false && $tokens[$i]['code'] === T_COMMA) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), $closeBracket, true); + if ($next === false) { + continue; + } + + if ($this->allowMultipleArguments === false) { + // Comma has to be the last token on the line. + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + $error = 'Only one argument is allowed per line in a multi-line function call'; + $fix = $phpcsFile->addFixableError($error, $next, 'MultipleArguments'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($next - 1); $x > $i; $x--) { + if ($tokens[$x]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContentBefore( + $next, + $phpcsFile->eolChar.str_repeat(' ', ($foundFunctionIndent + $this->indent)) + ); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + $argStart = $next; + $argEnd = $phpcsFile->findEndOfStatement($next, [T_COLON]); + }//end if + }//end for + + }//end processMultiLineCall() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionDeclarationSniff.php new file mode 100644 index 0000000..548565f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionDeclarationSniff.php @@ -0,0 +1,546 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\OpeningFunctionBraceBsdAllmanSniff; +use PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\OpeningFunctionBraceKernighanRitchieSniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionDeclarationSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + || $tokens[$stackPtr]['parenthesis_opener'] === null + || $tokens[$stackPtr]['parenthesis_closer'] === null + ) { + return; + } + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + + if (strtolower($tokens[$stackPtr]['content']) === 'function') { + // Must be one space after the FUNCTION keyword. + if ($tokens[($stackPtr + 1)]['content'] === $phpcsFile->eolChar) { + $spaces = 'newline'; + } else if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $spaces = $tokens[($stackPtr + 1)]['length']; + } else { + $spaces = 0; + } + + if ($spaces !== 1) { + $error = 'Expected 1 space after FUNCTION keyword; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterFunction', $data); + if ($fix === true) { + if ($spaces === 0) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } else { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } + }//end if + + // Must be no space before the opening parenthesis. For closures, this is + // enforced by the previous check because there is no content between the keywords + // and the opening parenthesis. + // Unfinished closures are tokenized as T_FUNCTION however, and can be excluded + // by checking for the scope_opener. + if ($tokens[$stackPtr]['code'] === T_FUNCTION + && (isset($tokens[$stackPtr]['scope_opener']) === true || $phpcsFile->getMethodProperties($stackPtr)['has_body'] === false) + ) { + if ($tokens[($openBracket - 1)]['content'] === $phpcsFile->eolChar) { + $spaces = 'newline'; + } else if ($tokens[($openBracket - 1)]['code'] === T_WHITESPACE) { + $spaces = $tokens[($openBracket - 1)]['length']; + } else { + $spaces = 0; + } + + if ($spaces !== 0) { + $error = 'Expected 0 spaces before opening parenthesis; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $openBracket, 'SpaceBeforeOpenParen', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($openBracket - 1), ''); + } + } + + // Must be no space before semicolon in abstract/interface methods. + if ($phpcsFile->getMethodProperties($stackPtr)['has_body'] === false) { + $end = $phpcsFile->findNext(T_SEMICOLON, $closeBracket); + if ($tokens[($end - 1)]['content'] === $phpcsFile->eolChar) { + $spaces = 'newline'; + } else if ($tokens[($end - 1)]['code'] === T_WHITESPACE) { + $spaces = $tokens[($end - 1)]['length']; + } else { + $spaces = 0; + } + + if ($spaces !== 0) { + $error = 'Expected 0 spaces before semicolon; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $end, 'SpaceBeforeSemicolon', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($end - 1), ''); + } + } + } + }//end if + + // Must be one space before and after USE keyword for closures. + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + if ($tokens[($use + 1)]['code'] !== T_WHITESPACE) { + $length = 0; + } else if ($tokens[($use + 1)]['content'] === "\t") { + $length = '\t'; + } else { + $length = $tokens[($use + 1)]['length']; + } + + if ($length !== 1) { + $error = 'Expected 1 space after USE keyword; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $use, 'SpaceAfterUse', $data); + if ($fix === true) { + if ($length === 0) { + $phpcsFile->fixer->addContent($use, ' '); + } else { + $phpcsFile->fixer->replaceToken(($use + 1), ' '); + } + } + } + + if ($tokens[($use - 1)]['code'] !== T_WHITESPACE) { + $length = 0; + } else if ($tokens[($use - 1)]['content'] === "\t") { + $length = '\t'; + } else { + $length = $tokens[($use - 1)]['length']; + } + + if ($length !== 1) { + $error = 'Expected 1 space before USE keyword; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $use, 'SpaceBeforeUse', $data); + if ($fix === true) { + if ($length === 0) { + $phpcsFile->fixer->addContentBefore($use, ' '); + } else { + $phpcsFile->fixer->replaceToken(($use - 1), ' '); + } + } + } + }//end if + }//end if + + if ($this->isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) === true) { + $this->processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens); + } else { + $this->processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens); + } + + }//end process() + + + /** + * Determine if this is a multi-line function declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return bool + */ + public function isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) + { + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + if ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']) { + return true; + } + + // Closures may use the USE keyword and so be multi-line in this way. + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + // If the opening and closing parenthesis of the use statement + // are also on the same line, this is a single line declaration. + $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + $close = $tokens[$open]['parenthesis_closer']; + if ($tokens[$open]['line'] !== $tokens[$close]['line']) { + return true; + } + } + } + + return false; + + }//end isMultiLineDeclaration() + + + /** + * Processes single-line declarations. + * + * Just uses the Generic BSD-Allman brace sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens) + { + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $sniff = new OpeningFunctionBraceKernighanRitchieSniff(); + } else { + $sniff = new OpeningFunctionBraceBsdAllmanSniff(); + } + + $sniff->checkClosures = true; + $sniff->process($phpcsFile, $stackPtr); + + }//end processSingleLineDeclaration() + + + /** + * Processes multi-line declarations. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens) + { + $this->processArgumentList($phpcsFile, $stackPtr, $this->indent); + + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + $closeBracket = $tokens[$open]['parenthesis_closer']; + } + } + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + // The opening brace needs to be on the same line as the closing parenthesis. + // There should only be one space between the closing parenthesis - or the end of the + // return type - and the opening brace. + $opener = $tokens[$stackPtr]['scope_opener']; + if ($tokens[$opener]['line'] !== $tokens[$closeBracket]['line']) { + $error = 'The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line'; + $code = 'NewlineBeforeOpenBrace'; + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($opener - 1), $closeBracket, true); + if ($tokens[$prev]['line'] === $tokens[$opener]['line']) { + // End of the return type is not on the same line as the close parenthesis. + $phpcsFile->addError($error, $opener, $code); + } else { + $fix = $phpcsFile->addFixableError($error, $opener, $code); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($prev, ' {'); + + // If the opener is on a line by itself, removing it will create + // an empty line, so remove the entire line instead. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($opener - 1), $closeBracket, true); + $next = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true); + + if ($tokens[$prev]['line'] < $tokens[$opener]['line'] + && $tokens[$next]['line'] > $tokens[$opener]['line'] + ) { + // Clear the whole line. + for ($i = ($prev + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$opener]['line']) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + } else { + // Just remove the opener. + $phpcsFile->fixer->replaceToken($opener, ''); + if ($tokens[$next]['line'] === $tokens[$opener]['line'] + && ($opener + 1) !== $next + ) { + $phpcsFile->fixer->replaceToken(($opener + 1), ''); + } + } + + $phpcsFile->fixer->endChangeset(); + }//end if + + return; + }//end if + }//end if + + $prev = $tokens[($opener - 1)]; + if ($prev['code'] !== T_WHITESPACE) { + $length = 0; + } else { + $length = strlen($prev['content']); + } + + if ($length !== 1) { + $error = 'There must be a single space between the closing parenthesis/return type and the opening brace of a multi-line function declaration; found %s spaces'; + $fix = $phpcsFile->addFixableError($error, ($opener - 1), 'SpaceBeforeOpenBrace', [$length]); + if ($fix === true) { + if ($length === 0) { + $phpcsFile->fixer->addContentBefore($opener, ' '); + } else { + $phpcsFile->fixer->replaceToken(($opener - 1), ' '); + } + } + } + + }//end processMultiLineDeclaration() + + + /** + * Processes multi-line argument list declarations. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $indent The number of spaces code should be indented. + * @param string $type The type of the token the brackets + * belong to. + * + * @return void + */ + public function processArgumentList($phpcsFile, $stackPtr, $indent, $type='function') + { + $tokens = $phpcsFile->getTokens(); + + // We need to work out how far indented the function + // declaration itself is, so we can work out how far to + // indent parameters. + $functionIndent = 0; + for ($i = ($stackPtr - 1); $i >= 0; $i--) { + if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) { + break; + } + } + + // Move $i back to the line the function is or to 0. + $i++; + + if ($tokens[$i]['code'] === T_WHITESPACE) { + $functionIndent = $tokens[$i]['length']; + } + + // The closing parenthesis must be on a new line, even + // when checking abstract function definitions. + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + $prev = $phpcsFile->findPrevious( + T_WHITESPACE, + ($closeBracket - 1), + null, + true + ); + + if ($tokens[$closeBracket]['line'] !== $tokens[$tokens[$closeBracket]['parenthesis_opener']]['line'] + && $tokens[$prev]['line'] === $tokens[$closeBracket]['line'] + ) { + $error = 'The closing parenthesis of a multi-line '.$type.' declaration must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'CloseBracketLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($closeBracket); + } + } + + // If this is a closure and is using a USE statement, the closing + // parenthesis we need to look at from now on is the closing parenthesis + // of the USE statement. + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + $closeBracket = $tokens[$open]['parenthesis_closer']; + + $prev = $phpcsFile->findPrevious( + T_WHITESPACE, + ($closeBracket - 1), + null, + true + ); + + if ($tokens[$closeBracket]['line'] !== $tokens[$tokens[$closeBracket]['parenthesis_opener']]['line'] + && $tokens[$prev]['line'] === $tokens[$closeBracket]['line'] + ) { + $error = 'The closing parenthesis of a multi-line use declaration must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'UseCloseBracketLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($closeBracket); + } + } + }//end if + }//end if + + // Each line between the parenthesis should be indented 4 spaces. + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $lastLine = $tokens[$openBracket]['line']; + for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { + if ($tokens[$i]['line'] !== $lastLine) { + if ($i === $tokens[$stackPtr]['parenthesis_closer'] + || ($tokens[$i]['code'] === T_WHITESPACE + && (($i + 1) === $closeBracket + || ($i + 1) === $tokens[$stackPtr]['parenthesis_closer'])) + ) { + // Closing braces need to be indented to the same level + // as the function. + $expectedIndent = $functionIndent; + } else { + $expectedIndent = ($functionIndent + $indent); + } + + // We changed lines, so this should be a whitespace indent token. + $foundIndent = 0; + if ($tokens[$i]['code'] === T_WHITESPACE + && $tokens[$i]['line'] !== $tokens[($i + 1)]['line'] + ) { + $error = 'Blank lines are not allowed in a multi-line '.$type.' declaration'; + $fix = $phpcsFile->addFixableError($error, $i, 'EmptyLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + // This is an empty line, so don't check the indent. + continue; + } else if ($tokens[$i]['code'] === T_WHITESPACE) { + $foundIndent = $tokens[$i]['length']; + } else if ($tokens[$i]['code'] === T_DOC_COMMENT_WHITESPACE) { + $foundIndent = $tokens[$i]['length']; + ++$expectedIndent; + } + + if ($expectedIndent !== $foundIndent) { + $error = 'Multi-line '.$type.' declaration not indented correctly; expected %s spaces but found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $i, 'Indent', $data); + if ($fix === true) { + $spaces = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($i, $spaces); + } else { + $phpcsFile->fixer->replaceToken($i, $spaces); + } + } + } + + $lastLine = $tokens[$i]['line']; + }//end if + + if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS + && isset($tokens[$i]['parenthesis_closer']) === true + ) { + $prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), null, true); + if ($tokens[$prevNonEmpty]['code'] !== T_USE) { + // Since PHP 8.1, a default value can contain a class instantiation. + // Skip over these "function calls" as they have their own indentation rules. + $i = $tokens[$i]['parenthesis_closer']; + $lastLine = $tokens[$i]['line']; + continue; + } + } + + if ($tokens[$i]['code'] === T_ARRAY || $tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { + // Skip arrays as they have their own indentation rules. + if ($tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { + $i = $tokens[$i]['bracket_closer']; + } else { + $i = $tokens[$i]['parenthesis_closer']; + } + + $lastLine = $tokens[$i]['line']; + continue; + } + + if ($tokens[$i]['code'] === T_ATTRIBUTE) { + // Skip attributes as they have their own indentation rules. + $i = $tokens[$i]['attribute_closer']; + $lastLine = $tokens[$i]['line']; + continue; + } + }//end for + + }//end processArgumentList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/ValidDefaultValueSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/ValidDefaultValueSniff.php new file mode 100644 index 0000000..9952daa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/ValidDefaultValueSniff.php @@ -0,0 +1,78 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ValidDefaultValueSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + T_FN, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // Flag for when we have found a default in our arg list. + // If there is a value without a default after this, it is an error. + $defaultFound = false; + + $params = $phpcsFile->getMethodParameters($stackPtr); + foreach ($params as $param) { + if ($param['variable_length'] === true) { + continue; + } + + if (array_key_exists('default', $param) === true) { + $defaultFound = true; + // Check if the arg is type hinted and using NULL for the default. + // This does not make the argument optional - it just allows NULL + // to be passed in. + if ($param['type_hint'] !== '' && strtolower($param['default']) === 'null') { + $defaultFound = false; + } + + continue; + } + + if ($defaultFound === true) { + $error = 'Arguments with default values must be at the end of the argument list'; + $phpcsFile->addError($error, $param['token'], 'NotAtEnd'); + return; + } + }//end foreach + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidClassNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidClassNameSniff.php new file mode 100644 index 0000000..c2ed80a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidClassNameSniff.php @@ -0,0 +1,98 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ValidClassNameSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being processed. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $className = $phpcsFile->findNext(T_STRING, $stackPtr); + $name = trim($tokens[$className]['content']); + $errorData = [ucfirst($tokens[$stackPtr]['content'])]; + + // Make sure the first letter is a capital. + if (preg_match('|^[A-Z]|', $name) === 0) { + $error = '%s name must begin with a capital letter'; + $phpcsFile->addError($error, $stackPtr, 'StartWithCapital', $errorData); + } + + // Check that each new word starts with a capital as well, but don't + // check the first word, as it is checked above. + $validName = true; + $nameBits = explode('_', $name); + $firstBit = array_shift($nameBits); + foreach ($nameBits as $bit) { + if ($bit === '' || $bit[0] !== strtoupper($bit[0])) { + $validName = false; + break; + } + } + + if ($validName === false) { + // Strip underscores because they cause the suggested name + // to be incorrect. + $nameBits = explode('_', trim($name, '_')); + $firstBit = array_shift($nameBits); + if ($firstBit === '') { + $error = '%s name is not valid'; + $phpcsFile->addError($error, $stackPtr, 'Invalid', $errorData); + } else { + $newName = strtoupper($firstBit[0]).substr($firstBit, 1).'_'; + foreach ($nameBits as $bit) { + if ($bit !== '') { + $newName .= strtoupper($bit[0]).substr($bit, 1).'_'; + } + } + + $newName = rtrim($newName, '_'); + $error = '%s name is not valid; consider %s instead'; + $data = $errorData; + $data[] = $newName; + $phpcsFile->addError($error, $stackPtr, 'Invalid', $data); + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidFunctionNameSniff.php new file mode 100644 index 0000000..b1521aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -0,0 +1,284 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Tokens; + +class ValidFunctionNameSniff extends AbstractScopeSniff +{ + + /** + * A list of all PHP magic methods. + * + * @var array + */ + protected $magicMethods = [ + 'construct' => true, + 'destruct' => true, + 'call' => true, + 'callstatic' => true, + 'get' => true, + 'set' => true, + 'isset' => true, + 'unset' => true, + 'sleep' => true, + 'wakeup' => true, + 'serialize' => true, + 'unserialize' => true, + 'tostring' => true, + 'invoke' => true, + 'set_state' => true, + 'clone' => true, + 'debuginfo' => true, + ]; + + /** + * A list of all PHP magic functions. + * + * @var array + */ + protected $magicFunctions = ['autoload' => true]; + + + /** + * Constructs a PEAR_Sniffs_NamingConventions_ValidFunctionNameSniff. + */ + public function __construct() + { + parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION], true); + + }//end __construct() + + + /** + * Processes the tokens within the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * @param int $currScope The position of the current scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + + $className = $phpcsFile->getDeclarationName($currScope); + if (isset($className) === false) { + $className = '[Anonymous Class]'; + } + + $errorData = [$className.'::'.$methodName]; + + $methodNameLc = strtolower($methodName); + $classNameLc = strtolower($className); + + // Is this a magic method. i.e., is prefixed with "__" ? + if (preg_match('|^__[^_]|', $methodName) !== 0) { + $magicPart = substr($methodNameLc, 2); + if (isset($this->magicMethods[$magicPart]) === true) { + return; + } + + $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'MethodDoubleUnderscore', $errorData); + } + + // PHP4 constructors are allowed to break our rules. + if ($methodNameLc === $classNameLc) { + return; + } + + // PHP4 destructors are allowed to break our rules. + if ($methodNameLc === '_'.$classNameLc) { + return; + } + + $methodProps = $phpcsFile->getMethodProperties($stackPtr); + $scope = $methodProps['scope']; + $scopeSpecified = $methodProps['scope_specified']; + + if ($methodProps['scope'] === 'private') { + $isPublic = false; + } else { + $isPublic = true; + } + + // If it's a private method, it must have an underscore on the front. + if ($isPublic === false) { + if ($methodName[0] !== '_') { + $error = 'Private method name "%s" must be prefixed with an underscore'; + $phpcsFile->addError($error, $stackPtr, 'PrivateNoUnderscore', $errorData); + $phpcsFile->recordMetric($stackPtr, 'Private method prefixed with underscore', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Private method prefixed with underscore', 'yes'); + } + } + + // If it's not a private method, it must not have an underscore on the front. + if ($isPublic === true && $scopeSpecified === true && $methodName[0] === '_') { + $error = '%s method name "%s" must not be prefixed with an underscore'; + $data = [ + ucfirst($scope), + $errorData[0], + ]; + $phpcsFile->addError($error, $stackPtr, 'PublicUnderscore', $data); + } + + $testMethodName = ltrim($methodName, '_'); + + if (Common::isCamelCaps($testMethodName, false, true, false) === false) { + if ($scopeSpecified === true) { + $error = '%s method name "%s" is not in camel caps format'; + $data = [ + ucfirst($scope), + $errorData[0], + ]; + $phpcsFile->addError($error, $stackPtr, 'ScopeNotCamelCaps', $data); + } else { + $error = 'Method name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + } + } + + }//end processTokenWithinScope() + + + /** + * Processes the tokens outside the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $functionName = $phpcsFile->getDeclarationName($stackPtr); + if ($functionName === null) { + // Ignore closures. + return; + } + + if (ltrim($functionName, '_') === '') { + // Ignore special functions. + return; + } + + $errorData = [$functionName]; + + // Is this a magic function. i.e., it is prefixed with "__". + if (preg_match('|^__[^_]|', $functionName) !== 0) { + $magicPart = strtolower(substr($functionName, 2)); + if (isset($this->magicFunctions[$magicPart]) === true) { + return; + } + + $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'FunctionDoubleUnderscore', $errorData); + } + + // Function names can be in two parts; the package name and + // the function name. + $packagePart = ''; + $underscorePos = strrpos($functionName, '_'); + if ($underscorePos === false) { + $camelCapsPart = $functionName; + } else { + $packagePart = substr($functionName, 0, $underscorePos); + $camelCapsPart = substr($functionName, ($underscorePos + 1)); + + // We don't care about _'s on the front. + $packagePart = ltrim($packagePart, '_'); + } + + // If it has a package part, make sure the first letter is a capital. + if ($packagePart !== '') { + if ($functionName[0] === '_') { + $error = 'Function name "%s" is invalid; only private methods should be prefixed with an underscore'; + $phpcsFile->addError($error, $stackPtr, 'FunctionUnderscore', $errorData); + } + + if ($functionName[0] !== strtoupper($functionName[0])) { + $error = 'Function name "%s" is prefixed with a package name but does not begin with a capital letter'; + $phpcsFile->addError($error, $stackPtr, 'FunctionNoCapital', $errorData); + } + } + + // If it doesn't have a camel caps part, it's not valid. + if (trim($camelCapsPart) === '') { + $error = 'Function name "%s" is not valid; name appears incomplete'; + $phpcsFile->addError($error, $stackPtr, 'FunctionInvalid', $errorData); + return; + } + + $validName = true; + $newPackagePart = $packagePart; + $newCamelCapsPart = $camelCapsPart; + + // Every function must have a camel caps part, so check that first. + if (Common::isCamelCaps($camelCapsPart, false, true, false) === false) { + $validName = false; + $newCamelCapsPart = strtolower($camelCapsPart[0]).substr($camelCapsPart, 1); + } + + if ($packagePart !== '') { + // Check that each new word starts with a capital. + $nameBits = explode('_', $packagePart); + $nameBits = array_filter($nameBits); + foreach ($nameBits as $bit) { + if ($bit[0] !== strtoupper($bit[0])) { + $newPackagePart = ''; + foreach ($nameBits as $bit) { + $newPackagePart .= strtoupper($bit[0]).substr($bit, 1).'_'; + } + + $validName = false; + break; + } + } + } + + if ($validName === false) { + if ($newPackagePart === '') { + $newName = $newCamelCapsPart; + } else { + $newName = rtrim($newPackagePart, '_').'_'.$newCamelCapsPart; + } + + $error = 'Function name "%s" is invalid; consider "%s" instead'; + $data = $errorData; + $data[] = $newName; + $phpcsFile->addError($error, $stackPtr, 'FunctionNameInvalid', $data); + } + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidVariableNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidVariableNameSniff.php new file mode 100644 index 0000000..48674b1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -0,0 +1,103 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; + +class ValidVariableNameSniff extends AbstractVariableSniff +{ + + + /** + * Processes class member variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $memberProps = $phpcsFile->getMemberProperties($stackPtr); + if (empty($memberProps) === true) { + return; + } + + $memberName = ltrim($tokens[$stackPtr]['content'], '$'); + $scope = $memberProps['scope']; + $scopeSpecified = $memberProps['scope_specified']; + + if ($memberProps['scope'] === 'private') { + $isPublic = false; + } else { + $isPublic = true; + } + + // If it's a private member, it must have an underscore on the front. + if ($isPublic === false && $memberName[0] !== '_') { + $error = 'Private member variable "%s" must be prefixed with an underscore'; + $data = [$memberName]; + $phpcsFile->addError($error, $stackPtr, 'PrivateNoUnderscore', $data); + return; + } + + // If it's not a private member, it must not have an underscore on the front. + if ($isPublic === true && $scopeSpecified === true && $memberName[0] === '_') { + $error = '%s member variable "%s" must not be prefixed with an underscore'; + $data = [ + ucfirst($scope), + $memberName, + ]; + $phpcsFile->addError($error, $stackPtr, 'PublicUnderscore', $data); + return; + } + + }//end processMemberVar() + + + /** + * Processes normal variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariable() + + + /** + * Processes variables in double quoted strings. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ObjectOperatorIndentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ObjectOperatorIndentSniff.php new file mode 100644 index 0000000..9c64c32 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ObjectOperatorIndentSniff.php @@ -0,0 +1,204 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ObjectOperatorIndentSniff implements Sniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + /** + * Indicates whether multilevel indenting is allowed. + * + * @var boolean + */ + public $multilevel = false; + + /** + * Tokens to listen for. + * + * @var array + */ + private $targets = [ + T_OBJECT_OPERATOR, + T_NULLSAFE_OBJECT_OPERATOR, + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return $this->targets; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile All the tokens found in the document. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Make sure this is the first object operator in a chain of them. + $start = $phpcsFile->findStartOfStatement($stackPtr); + $prev = $phpcsFile->findPrevious($this->targets, ($stackPtr - 1), $start); + if ($prev !== false) { + return; + } + + // Make sure this is a chained call. + $end = $phpcsFile->findEndOfStatement($stackPtr); + $next = $phpcsFile->findNext($this->targets, ($stackPtr + 1), $end); + if ($next === false) { + // Not a chained call. + return; + } + + // Determine correct indent. + for ($i = ($start - 1); $i >= 0; $i--) { + if ($tokens[$i]['line'] !== $tokens[$start]['line']) { + $i++; + break; + } + } + + $baseIndent = 0; + if ($i >= 0 && $tokens[$i]['code'] === T_WHITESPACE) { + $baseIndent = $tokens[$i]['length']; + } + + $baseIndent += $this->indent; + + // Determine the scope of the original object operator. + $origBrackets = null; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $origBrackets = $tokens[$stackPtr]['nested_parenthesis']; + } + + $origConditions = null; + if (isset($tokens[$stackPtr]['conditions']) === true) { + $origConditions = $tokens[$stackPtr]['conditions']; + } + + // Check indentation of each object operator in the chain. + // If the first object operator is on a different line than + // the variable, make sure we check its indentation too. + if ($tokens[$stackPtr]['line'] > $tokens[$start]['line']) { + $next = $stackPtr; + } + + $previousIndent = $baseIndent; + + while ($next !== false) { + // Make sure it is in the same scope, otherwise don't check indent. + $brackets = null; + if (isset($tokens[$next]['nested_parenthesis']) === true) { + $brackets = $tokens[$next]['nested_parenthesis']; + } + + $conditions = null; + if (isset($tokens[$next]['conditions']) === true) { + $conditions = $tokens[$next]['conditions']; + } + + if ($origBrackets === $brackets && $origConditions === $conditions) { + // Make sure it starts a line, otherwise don't check indent. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($next - 1), $stackPtr, true); + $indent = $tokens[($next - 1)]; + if ($tokens[$prev]['line'] !== $tokens[$next]['line'] + && $indent['code'] === T_WHITESPACE + ) { + if ($indent['line'] === $tokens[$next]['line']) { + $foundIndent = strlen($indent['content']); + } else { + $foundIndent = 0; + } + + $minIndent = $previousIndent; + $maxIndent = $previousIndent; + $expectedIndent = $previousIndent; + + if ($this->multilevel === true) { + $minIndent = max(($previousIndent - $this->indent), $baseIndent); + $maxIndent = ($previousIndent + $this->indent); + $expectedIndent = min(max($foundIndent, $minIndent), $maxIndent); + } + + if ($foundIndent < $minIndent || $foundIndent > $maxIndent) { + $error = 'Object operator not indented correctly; expected %s spaces but found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $next, 'Incorrect', $data); + if ($fix === true) { + $spaces = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($next, $spaces); + } else { + $phpcsFile->fixer->replaceToken(($next - 1), $spaces); + } + } + } + + $previousIndent = $expectedIndent; + }//end if + + // It cant be the last thing on the line either. + $content = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true); + if ($tokens[$content]['line'] !== $tokens[$next]['line']) { + $error = 'Object operator must be at the start of the line, not the end'; + $fix = $phpcsFile->addFixableError($error, $next, 'StartOfLine'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($next + 1); $x < $content; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addNewlineBefore($next); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + $next = $phpcsFile->findNext( + $this->targets, + ($next + 1), + null, + false, + null, + true + ); + }//end while + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php new file mode 100644 index 0000000..dd39532 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php @@ -0,0 +1,179 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ScopeClosingBraceSniff implements Sniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$scopeOpeners; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile All the tokens found in the document. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // If this is an inline condition (ie. there is no scope opener), then + // return, as this is not a new scope. + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $scopeStart = $tokens[$stackPtr]['scope_opener']; + $scopeEnd = $tokens[$stackPtr]['scope_closer']; + + // If the scope closer doesn't think it belongs to this scope opener + // then the opener is sharing its closer with other tokens. We only + // want to process the closer once, so skip this one. + if (isset($tokens[$scopeEnd]['scope_condition']) === false + || $tokens[$scopeEnd]['scope_condition'] !== $stackPtr + ) { + return; + } + + // We need to actually find the first piece of content on this line, + // because if this is a method with tokens before it (public, static etc) + // or an if with an else before it, then we need to start the scope + // checking from there, rather than the current token. + $lineStart = ($stackPtr - 1); + for ($lineStart; $lineStart > 0; $lineStart--) { + if (strpos($tokens[$lineStart]['content'], $phpcsFile->eolChar) !== false) { + break; + } + } + + $lineStart++; + + $startColumn = 1; + if ($tokens[$lineStart]['code'] === T_WHITESPACE) { + $startColumn = $tokens[($lineStart + 1)]['column']; + } else if ($tokens[$lineStart]['code'] === T_INLINE_HTML) { + $trimmed = ltrim($tokens[$lineStart]['content']); + if ($trimmed === '') { + $startColumn = $tokens[($lineStart + 1)]['column']; + } else { + $startColumn = (strlen($tokens[$lineStart]['content']) - strlen($trimmed)); + } + } + + // Check that the closing brace is on it's own line. + $lastContent = $phpcsFile->findPrevious( + [ + T_WHITESPACE, + T_INLINE_HTML, + T_OPEN_TAG, + ], + ($scopeEnd - 1), + $scopeStart, + true + ); + + if ($tokens[$lastContent]['line'] === $tokens[$scopeEnd]['line']) { + $error = 'Closing brace must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $scopeEnd, 'Line'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($scopeEnd); + } + + return; + } + + // Check now that the closing brace is lined up correctly. + $lineStart = ($scopeEnd - 1); + for ($lineStart; $lineStart > 0; $lineStart--) { + if (strpos($tokens[$lineStart]['content'], $phpcsFile->eolChar) !== false) { + break; + } + } + + $lineStart++; + + $braceIndent = 0; + if ($tokens[$lineStart]['code'] === T_WHITESPACE) { + $braceIndent = ($tokens[($lineStart + 1)]['column'] - 1); + } else if ($tokens[$lineStart]['code'] === T_INLINE_HTML) { + $trimmed = ltrim($tokens[$lineStart]['content']); + if ($trimmed === '') { + $braceIndent = ($tokens[($lineStart + 1)]['column'] - 1); + } else { + $braceIndent = (strlen($tokens[$lineStart]['content']) - strlen($trimmed) - 1); + } + } + + $fix = false; + if ($tokens[$stackPtr]['code'] === T_CASE + || $tokens[$stackPtr]['code'] === T_DEFAULT + ) { + // BREAK statements should be indented n spaces from the + // CASE or DEFAULT statement. + $expectedIndent = ($startColumn + $this->indent - 1); + if ($braceIndent !== $expectedIndent) { + $error = 'Case breaking statement indented incorrectly; expected %s spaces, found %s'; + $data = [ + $expectedIndent, + $braceIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $scopeEnd, 'BreakIndent', $data); + } + } else { + $expectedIndent = max(0, ($startColumn - 1)); + if ($braceIndent !== $expectedIndent) { + $error = 'Closing brace indented incorrectly; expected %s spaces, found %s'; + $data = [ + $expectedIndent, + $braceIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $scopeEnd, 'Indent', $data); + } + }//end if + + if ($fix === true) { + $spaces = str_repeat(' ', $expectedIndent); + if ($braceIndent === 0) { + $phpcsFile->fixer->addContentBefore($lineStart, $spaces); + } else { + $phpcsFile->fixer->replaceToken($lineStart, ltrim($tokens[$lineStart]['content'])); + $phpcsFile->fixer->addContentBefore($lineStart, $spaces); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeIndentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeIndentSniff.php new file mode 100644 index 0000000..e95dc8b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeIndentSniff.php @@ -0,0 +1,24 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff as GenericScopeIndentSniff; + +class ScopeIndentSniff extends GenericScopeIndentSniff +{ + + /** + * Any scope openers that should not cause an indent. + * + * @var int[] + */ + protected $nonIndentingScopes = [T_SWITCH]; + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc new file mode 100644 index 0000000..6942944 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc @@ -0,0 +1,114 @@ +setLogger(new class {}); + +var_dump(new class(10) extends SomeClass implements SomeInterface { + private $num; + + public function __construct($num) + { + $this->num = $num; + } + + use SomeTrait; +}); + +class IncorrectClassDeclarationWithCommentAtEnd extends correctClassDeclaration /* Comment */ { +} + +class CorrectClassDeclarationWithCommentAtEnd extends correctClassDeclaration +/* Comment */ +{ +} + +// Don't move phpcs:ignore comments. +class PHPCSIgnoreAnnotationAfterOpeningBrace +{ // phpcs:ignore Standard.Cat.Sniff -- for reasons. +} + +// Moving any of the other trailing phpcs: comments is ok. +class PHPCSAnnotationAfterOpeningBrace +{ // phpcs:disable Standard.Cat.Sniff -- for reasons. +} + +if (!class_exists('ClassOpeningBraceShouldBeIndented')) { + abstract class ClassOpeningBraceShouldBeIndented +{ +} +} + +if (!class_exists('ClassOpeningBraceTooMuchIndentation')) { + final class ClassOpeningBraceTooMuchIndentation + { + } +} + +enum IncorrectBracePlacement {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc.fixed new file mode 100644 index 0000000..26688b1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.1.inc.fixed @@ -0,0 +1,125 @@ +setLogger(new class {}); + +var_dump(new class(10) extends SomeClass implements SomeInterface { + private $num; + + public function __construct($num) + { + $this->num = $num; + } + + use SomeTrait; +}); + +class IncorrectClassDeclarationWithCommentAtEnd extends correctClassDeclaration /* Comment */ +{ +} + +class CorrectClassDeclarationWithCommentAtEnd extends correctClassDeclaration +/* Comment */ +{ +} + +// Don't move phpcs:ignore comments. +class PHPCSIgnoreAnnotationAfterOpeningBrace +{ // phpcs:ignore Standard.Cat.Sniff -- for reasons. +} + +// Moving any of the other trailing phpcs: comments is ok. +class PHPCSAnnotationAfterOpeningBrace +{ + // phpcs:disable Standard.Cat.Sniff -- for reasons. +} + +if (!class_exists('ClassOpeningBraceShouldBeIndented')) { + abstract class ClassOpeningBraceShouldBeIndented + { +} +} + +if (!class_exists('ClassOpeningBraceTooMuchIndentation')) { + final class ClassOpeningBraceTooMuchIndentation + { + } +} + +enum IncorrectBracePlacement +{ +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.2.inc new file mode 100644 index 0000000..ac71fc9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Classes/ClassDeclarationUnitTest.2.inc @@ -0,0 +1,11 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Classes\ClassDeclarationSniff + */ +class ClassDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + if ($testFile === 'ClassDeclarationUnitTest.1.inc') { + return; + } + + $config->tabWidth = 4; + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ClassDeclarationUnitTest.1.inc': + return [ + 21 => 1, + 22 => 1, + 23 => 1, + 27 => 1, + 33 => 1, + 38 => 1, + 49 => 1, + 84 => 1, + 94 => 1, + 99 => 1, + 104 => 1, + 110 => 1, + 114 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + if ($testFile === 'ClassDeclarationUnitTest.2.inc') { + return [11 => 1]; + } + + return[]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.inc new file mode 100644 index 0000000..bd7d061 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.inc @@ -0,0 +1,163 @@ + + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version Release: 1.0 + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class Extra_Description_Newlines +{ + +}//end class + + +/** + * Sample class comment + * @category PHP + * @package PHP_CodeSniffer + * @author Greg Sherwood + * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @version + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +class Missing_Newlines_Before_Tags +{ + +}//end class + + +/** + * Simple class comment + * + * @category _wrong_category + * @package PHP_CodeSniffer + * @package ADDITIONAL PACKAGE TAG + * @subpackage SUBPACKAGE TAG + * @author Original Author + * @author Greg Sherwood gsherwood@squiz.net + * @author Mr T + * @author + * @copyright 1997~1994 The PHP Group + * @license http://www.php.net/license/3_0.txt + * @version INVALID VERSION CONTENT + * @see + * @see + * @link sdfsdf + * @see Net_Sample::Net_Sample() + * @see Net_Other + * @deprecated asd + * @unknown Unknown tag + * @since Class available since Release 1.2.0 + */ +class Checking_Tags +{ + class Sub_Class { + + }//end class + + +}//end class + + +/** + * + * + */ +class Empty_Class_Doc +{ + +}//end class + + +/** + * + * + */ +interface Empty_Interface_Doc +{ + +}//end interface + + +/** + * + * + */ +trait Empty_Trait_Doc +{ + +}//end trait + + +/** + * + * + */ +enum Empty_Enum_Doc +{ + +}//end enum + + +/** + * Sample class comment + * + * @category PHP + * @package PHP_CodeSniffer + * @author Greg Sherwood + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +#[Authenticate('admin_logged_in')] +class TodoController extends AbstractController implements MustBeLoggedInInterface +{ +} + +/** + * Docblock + * + * @category PHP + * @package PHP_CodeSniffer + * @author Greg Sherwood + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * @link http://pear.php.net/package/PHP_CodeSniffer + */ +abstract readonly class AbstractReadonlyWithDocblock {} + +/* + * Docblock + */ +readonly class ReadonlyWrongStyle {} + +readonly final class ReadonlyFinalWithoutDocblock {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.php new file mode 100644 index 0000000..7242176 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/ClassCommentUnitTest.php @@ -0,0 +1,78 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\ClassCommentSniff + */ +class ClassCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 15 => 1, + 51 => 1, + 63 => 1, + 65 => 2, + 66 => 1, + 68 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + 74 => 2, + 75 => 1, + 76 => 1, + 77 => 1, + 85 => 1, + 96 => 5, + 106 => 5, + 116 => 5, + 126 => 5, + 161 => 1, + 163 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 71 => 1, + 73 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.1.inc new file mode 100644 index 0000000..0b18fa3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.1.inc @@ -0,0 +1,53 @@ + +* @author Greg Sherwood gsherwood@squiz.net +* @author Mr T +* @author +* @copyright 1997~1994 The PHP Group +* @copyright 1997~1994 The PHP Group +* @license http://www.php.net/license/3_0.txt +* @see +* @see +* @version INVALID VERSION CONTENT +* @see Net_Sample::Net_Sample() +* @see Net_Other +* @deprecated asd +* @since Class available since Release 1.2.0 +* @summary An unknown summary tag +* @package '' +* @subpackage !! +* @author Code AUthor +*/ +require_once '/some/path.php'; +?> + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.2.inc new file mode 100644 index 0000000..8845eb1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FileCommentUnitTest.2.inc @@ -0,0 +1,9 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FileComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FileCommentSniff + */ +class FileCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FileCommentUnitTest.1.inc': + return [ + 21 => 1, + 23 => 2, + 24 => 1, + 26 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 32 => 2, + 33 => 1, + 34 => 1, + 35 => 1, + 40 => 2, + 41 => 2, + 43 => 1, + ]; + + case 'FileCommentUnitTest.2.inc': + case 'FileCommentUnitTest.3.inc': + case 'FileCommentUnitTest.4.inc': + return [1 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'FileCommentUnitTest.1.inc': + return [ + 29 => 1, + 30 => 1, + 34 => 1, + 43 => 1, + ]; + + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc new file mode 100644 index 0000000..a20ba3a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc @@ -0,0 +1,512 @@ + line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function foo(&$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Gettext. + * + */ +function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Complete a step. + * + * @param string $status Status of step to complete. + * @param array $array Array. + * @param string $note Optional note. + * + * @return void + */ +function completeStep($status, array $array = [Class1::class, 'test'], $note = '') { + echo 'foo'; +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +function myFunction(string $name1, string ...$name2) { +} + +/** + * Completely invalid format, but should not cause PHP notices. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Processes the test. + * + * @param PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ +function process(File $phpcsFile, $stackPtr) +{ + +}//end process() + +/** + * Processes the test. + * + * @param int $phpcsFile The PHP_CodeSniffer + * file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ +function process(File $phpcsFile, $stackPtr) +{ + +}//end process() + +/** + * @param (Foo&Bar)|null $a Comment. + * @param string $b Comment. + * + * @return void + */ +public function setTranslator($a, &$b): void +{ + $this->translator = $translator; +} + +// phpcs:set PEAR.Commenting.FunctionComment minimumVisibility protected +private function setTranslator2($a, &$b): void +{ + $this->translator = $translator; +} + +// phpcs:set PEAR.Commenting.FunctionComment minimumVisibility public +protected function setTranslator3($a, &$b): void +{ + $this->translator = $translator; +} + +private function setTranslator4($a, &$b): void +{ + $this->translator = $translator; +} + +class Bar { + /** + * The PHP5 constructor + * + * @return + */ + public function __construct() { + + } +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] __construct,__destruct + +class Something implements JsonSerializable { + /** + * Single attribute. + * + * @return mixed + */ + #[ReturnTypeWillChange] + public function jsonSerialize() {} + + /** + * Multiple attributes. + * + * @return Something + */ + #[AttributeA] + #[AttributeB] + public function methodName() {} + + /** + * Blank line between docblock and attribute. + * + * @return mixed + */ + + #[ReturnTypeWillChange] + public function blankLineDetectionA() {} + + /** + * Blank line between attribute and function declaration. + * + * @return mixed + */ + #[ReturnTypeWillChange] + + public function blankLineDetectionB() {} + + /** + * Blank line between both docblock and attribute and attribute and function declaration. + * + * @return mixed + */ + + #[ReturnTypeWillChange] + + public function blankLineDetectionC() {} +} + +class SpacingAfter { + /** + * There are multiple blank lines between this comment and the next function. + * + * @return void + */ + + + + + + + + + public function multipleBlankLines() {} + + /** + * There are multiple blank lines, and some "empty" lines with only + * spaces/tabs between this comment and the next function. + * + * @return void + */ + + + + + + + + + + public function multipleLinesSomeEmpty() {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc.fixed new file mode 100644 index 0000000..fc6d4f7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.inc.fixed @@ -0,0 +1,491 @@ + line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function foo(&$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Gettext. + * + */ +function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Complete a step. + * + * @param string $status Status of step to complete. + * @param array $array Array. + * @param string $note Optional note. + * + * @return void + */ +function completeStep($status, array $array = [Class1::class, 'test'], $note = '') { + echo 'foo'; +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +function myFunction(string $name1, string ...$name2) { +} + +/** + * Completely invalid format, but should not cause PHP notices. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Processes the test. + * + * @param PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ +function process(File $phpcsFile, $stackPtr) +{ + +}//end process() + +/** + * Processes the test. + * + * @param int $phpcsFile The PHP_CodeSniffer + * file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ +function process(File $phpcsFile, $stackPtr) +{ + +}//end process() + +/** + * @param (Foo&Bar)|null $a Comment. + * @param string $b Comment. + * + * @return void + */ +public function setTranslator($a, &$b): void +{ + $this->translator = $translator; +} + +// phpcs:set PEAR.Commenting.FunctionComment minimumVisibility protected +private function setTranslator2($a, &$b): void +{ + $this->translator = $translator; +} + +// phpcs:set PEAR.Commenting.FunctionComment minimumVisibility public +protected function setTranslator3($a, &$b): void +{ + $this->translator = $translator; +} + +private function setTranslator4($a, &$b): void +{ + $this->translator = $translator; +} + +class Bar { + /** + * The PHP5 constructor + * + * @return + */ + public function __construct() { + + } +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set PEAR.Commenting.FunctionComment specialMethods[] __construct,__destruct + +class Something implements JsonSerializable { + /** + * Single attribute. + * + * @return mixed + */ + #[ReturnTypeWillChange] + public function jsonSerialize() {} + + /** + * Multiple attributes. + * + * @return Something + */ + #[AttributeA] + #[AttributeB] + public function methodName() {} + + /** + * Blank line between docblock and attribute. + * + * @return mixed + */ + #[ReturnTypeWillChange] + public function blankLineDetectionA() {} + + /** + * Blank line between attribute and function declaration. + * + * @return mixed + */ + #[ReturnTypeWillChange] + public function blankLineDetectionB() {} + + /** + * Blank line between both docblock and attribute and attribute and function declaration. + * + * @return mixed + */ + #[ReturnTypeWillChange] + public function blankLineDetectionC() {} +} + +class SpacingAfter { + /** + * There are multiple blank lines between this comment and the next function. + * + * @return void + */ + public function multipleBlankLines() {} + + /** + * There are multiple blank lines, and some "empty" lines with only + * spaces/tabs between this comment and the next function. + * + * @return void + */ + public function multipleLinesSomeEmpty() {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.php new file mode 100644 index 0000000..bf379c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/FunctionCommentUnitTest.php @@ -0,0 +1,103 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FunctionCommentSniff + */ +class FunctionCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 10 => 1, + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + 28 => 1, + 76 => 1, + 87 => 1, + 103 => 1, + 109 => 1, + 112 => 1, + 122 => 1, + 123 => 2, + 124 => 2, + 125 => 1, + 126 => 1, + 137 => 1, + 138 => 1, + 139 => 1, + 152 => 1, + 155 => 1, + 165 => 1, + 172 => 1, + 183 => 1, + 190 => 2, + 206 => 1, + 234 => 1, + 272 => 1, + 313 => 1, + 317 => 1, + 327 => 1, + 329 => 1, + 332 => 1, + 344 => 1, + 343 => 1, + 345 => 1, + 346 => 1, + 360 => 1, + 361 => 1, + 363 => 1, + 364 => 1, + 406 => 1, + 417 => 1, + 455 => 1, + 464 => 1, + 473 => 1, + 485 => 1, + 501 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/InlineCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/InlineCommentUnitTest.inc new file mode 100644 index 0000000..187228c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Commenting/InlineCommentUnitTest.inc @@ -0,0 +1,29 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the InlineComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\InlineCommentSniff + */ +class InlineCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 15 => 1, + 24 => 1, + 25 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.inc new file mode 100644 index 0000000..cc9903a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.inc @@ -0,0 +1,165 @@ + 0); + +do +{ + echo $i; +} while ($i > 0); + +do +{ + echo $i; +} +while ($i > 0); + +do { echo $i; } while ($i > 0); + +do{ + echo $i; +}while($i > 0); + + +// while +while ($i < 1) { + echo $i; +} + +while($i < 1){ + echo $i; +} + +while ($i < 1) { echo $i; } + + +// for +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for($i = 1; $i < 1; $i++){ + echo $i; +} + +for ($i = 1; $i < 1; $i++) { echo $i; } + + +// foreach +foreach ($items as $item) { + echo $item; +} + +foreach($items as $item){ + echo $item; +} + +foreach ($items as $item) { echo $item; } + + +// if +if ($i == 0) { + $i = 1; +} + +if($i == 0){ + $i = 1; +} + +if ($i == 0) { $i = 1; } + + +// else +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else{ + $i = 0; +} + +if ($i == 0) { $i = 1; } else { $i = 0; } + + +// else +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else{ + $i = 0; +} + +if ($i == 0) { $i = 1; } else { $i = 0; } + + +// else if +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} elseif ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else if($i == 2){ + $i = 0; +} + +if ($i == 0) { + $i = 1; +}elseif($i == 2){ + $i = 0; +} + +if ($i == 0) { $i = 1; } else if ($i == 2) { $i = 0; } +if ($i == 0) { $i = 1; } elseif ($i == 2) { $i = 0; } + +if ($i == 0) { // this is ok because comments are allowed + $i = 1; +} + +if ($i == 0) {// this is ok because comments are allowed + $i = 1; +} + +if ($i == 0) { /* this is ok because comments are allowed*/ + $i = 1; +} + +if ($i == 0) +{ // this is not ok + $i = 1; +} + +if ($i == 0) /* this is ok */ { +} + +if ($i == 0) { +} +else { +} + +// match +$r = match ($x) { + 1 => 1, +}; + +$r = match( $x ){ 1 => 1 }; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.php new file mode 100644 index 0000000..ef8b946 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/ControlSignatureUnitTest.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ControlSignature sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\ControlStructures\ControlSignatureSniff + */ +class ControlSignatureUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 14 => 1, + 20 => 1, + 22 => 1, + 32 => 1, + 36 => 1, + 44 => 1, + 48 => 1, + 56 => 1, + 60 => 1, + 68 => 1, + 72 => 1, + 84 => 1, + 88 => 2, + 100 => 1, + 104 => 2, + 122 => 2, + 128 => 1, + 132 => 3, + 133 => 2, + 147 => 1, + 157 => 1, + 165 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc new file mode 100644 index 0000000..a7a3c69 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc @@ -0,0 +1,251 @@ + +

some text

+errorCode() == 401 || // comment + $IPP->errorCode() == 3200) /* long comment + here + */ +{ + return false; +} + +if ($IPP->errorCode() == 401 || // comment + $IPP->errorCode() == 3200) // long comment here +{ + return false; +} + +if ($IPP->errorCode() == 401 + // Comment explaining the next condition here. + || $IPP->errorCode() == 3200 +) { + return false; +} + +function bar() { + if ($a + && $b +) { + return false; + } +} + +if ($a + && foo( + 'a', + 'b' + )) { + return false; +} + +?> + + + + + +errorCode() == 401 || // phpcs:ignore Standard.Category.Sniff -- for reasons. + $IPP->errorCode() == 3200) /* + phpcs:ignore Standard.Category.Sniff -- for reasons. + */ +{ + return false; +} + +if ($IPP->errorCode() == 401 || // phpcs:disable Standard.Category.Sniff -- for reasons. + $IPP->errorCode() == 3200) // phpcs:enable +{ + return false; +} + +if ($IPP->errorCode() == 401 + // phpcs:ignore Standard.Category.Sniff -- for reasons. + || $IPP->errorCode() == 3200 +) { + return false; +} + + if ($IPP->errorCode() == 401 || + /* + * phpcs:disable Standard.Category.Sniff -- for reasons. + */ + $IPP->errorCode() == 3200 + ) { + return false; + } + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() == 3200 + // phpcs:ignore Standard.Category.Sniff -- for reasons. +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() + === 'someverylongexpectedoutput' +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() + // A comment. + === 'someverylongexpectedoutput' +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() + // phpcs:ignore Standard.Category.Sniff -- for reasons. + === 'someverylongexpectedoutput' +) { + return false; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc.fixed new file mode 100644 index 0000000..7d56c46 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.inc.fixed @@ -0,0 +1,247 @@ + +

some text

+errorCode() == 401 // comment + || $IPP->errorCode() == 3200 /* long comment + here + */ +) { + return false; +} + +if ($IPP->errorCode() == 401 // comment + || $IPP->errorCode() == 3200 // long comment here +) { + return false; +} + +if ($IPP->errorCode() == 401 + // Comment explaining the next condition here. + || $IPP->errorCode() == 3200 +) { + return false; +} + +function bar() { + if ($a + && $b + ) { + return false; + } +} + +if ($a + && foo( + 'a', + 'b' + ) +) { + return false; +} + +?> + + + + + +errorCode() == 401 // phpcs:ignore Standard.Category.Sniff -- for reasons. + || $IPP->errorCode() == 3200 /* + phpcs:ignore Standard.Category.Sniff -- for reasons. + */ +) { + return false; +} + +if ($IPP->errorCode() == 401 // phpcs:disable Standard.Category.Sniff -- for reasons. + || $IPP->errorCode() == 3200 // phpcs:enable +) { + return false; +} + +if ($IPP->errorCode() == 401 + // phpcs:ignore Standard.Category.Sniff -- for reasons. + || $IPP->errorCode() == 3200 +) { + return false; +} + + if ($IPP->errorCode() == 401 + /* + * phpcs:disable Standard.Category.Sniff -- for reasons. + */ + || $IPP->errorCode() == 3200 + ) { + return false; + } + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() == 3200 + // phpcs:ignore Standard.Category.Sniff -- for reasons. +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() === 'someverylongexpectedoutput' +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() + // A comment. + === 'someverylongexpectedoutput' +) { + return false; +} + +if ($IPP->errorCode() == 401 + || $IPP->errorCode() + // phpcs:ignore Standard.Category.Sniff -- for reasons. + === 'someverylongexpectedoutput' +) { + return false; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js new file mode 100644 index 0000000..064d7ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js @@ -0,0 +1,251 @@ +if (blah(param)) { + +} + +if ((condition1 + || condition2) + && condition3 + && condition4 + && condition5 +) { +} + +if ((condition1 || condition2) && condition3 && condition4 && condition5) { +} + +if ((condition1 || condition2) + && condition3 +) { +} + +if ( + (condition1 || condition2) + && condition3 +) { +} + +if ((condition1 + || condition2) +) { +} + +if ((condition1 + || condition2) + && condition3 && + condition4 +) { +} + +if ((condition1 + || condition2) + && condition3 + && condition4 + && condition5 +) { +} + +if (($condition1 + || $condition2) +) { +} + +if ((condition1 + || condition2) + ) { +} + +if ( + ( + condition1 + || condition2 + ) + && condition3 +) { +} + + +if ( condition1 + || condition2 + || condition3 +) { +} + +if (condition1 + || condition2 + || condition3 +) { +} else if (condition1 + || condition2 + || condition3 +) { +} + +if (condition1 + || condition2 + || condition3 +) { +} else if ( + condition1 + || condition2 && + condition3 +) { +} + +if (condition1 + || condition2 +|| condition3) { +} + +if (condition1 + || condition2 || condition3 +){ +} + +if (condition1) + console.info('bar'); + +if (condition1 + || condition2 +|| condition3) + console.info('bar'); + + +if (condition1 + || condition2 || condition3 +) + console.info('bar'); + +if (!a(post) + && (!a(context.header) + ^ a(context.header, 'Content-Type')) +) { +// ... +} + +if (foo) +{ + console.info('bar'); +} + +// Should be no errors even though lines are +// not exactly aligned together. Multi-line function +// call takes precedence. +if (array_key_exists(key, value) + && foo.bar.baz( + key, value2 + ) +) { +} + +if (true) { + foo = true; +}; + +if (foo == 401 || // comment + bar == 3200) /* long comment + here + */ +{ + return false; +} + +if (foo == 401 || // comment + bar == 3200) // long comment here +{ + return false; +} + +if (IPP.errorCode() == 401 + // Comment explaining the next condition here. + || IPP.errorCode() == 3200 +) { + return false; +} + +function bar() { + if (a + && b +) { + return false; + } +} + +if (a + && foo( + 'a', + 'b' + )) { + return false; +} + + + + + + + + + + + + + +if (foo == 401 || // phpcs:ignore Standard.Category.Sniff -- for reasons. + bar == 3200) /* + phpcs:ignore Standard.Category.Sniff -- for reasons. + */ +{ + return false; +} + +if (foo == 401 || // phpcs:disable Standard.Category.Sniff -- for reasons. + bar == 3200) // phpcs:enable +{ + return false; +} + +if (IPP.errorCode() == 401 + // phpcs:ignore Standard.Category.Sniff -- for reasons. + || IPP.errorCode() == 3200 +) { + return false; +} + + if (foo == 401 || + /* + * phpcs:disable Standard.Category.Sniff -- for reasons. + */ + bar == 3200 + ) { + return false; + } + +if (IPP.errorCode() == 401 + || IPP.errorCode() == 3200 + // phpcs:ignore Standard.Category.Sniff -- for reasons. +) { + return false; +} + +if (foo == 401 + || bar + == 'someverylongexpectedoutput' +) { + return false; +} + +if (IPP.errorCode() == 401 + || bar + // A comment. + == 'someverylongexpectedoutput' +) { + return false; +} + +if (foo == 401 + || IPP.errorCode() + // phpcs:ignore Standard.Category.Sniff -- for reasons. + == 'someverylongexpectedoutput' +) { + return false; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js.fixed new file mode 100644 index 0000000..cfde75d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.js.fixed @@ -0,0 +1,247 @@ +if (blah(param)) { + +} + +if ((condition1 + || condition2) + && condition3 + && condition4 + && condition5 +) { +} + +if ((condition1 || condition2) && condition3 && condition4 && condition5) { +} + +if ((condition1 || condition2) + && condition3 +) { +} + +if ((condition1 || condition2) + && condition3 +) { +} + +if ((condition1 + || condition2) +) { +} + +if ((condition1 + || condition2) + && condition3 + && condition4 +) { +} + +if ((condition1 + || condition2) + && condition3 + && condition4 + && condition5 +) { +} + +if (($condition1 + || $condition2) +) { +} + +if ((condition1 + || condition2) +) { +} + +if ((condition1 + || condition2) + && condition3 +) { +} + + +if (condition1 + || condition2 + || condition3 +) { +} + +if (condition1 + || condition2 + || condition3 +) { +} else if (condition1 + || condition2 + || condition3 +) { +} + +if (condition1 + || condition2 + || condition3 +) { +} else if (condition1 + || condition2 + && condition3 +) { +} + +if (condition1 + || condition2 + || condition3 +) { +} + +if (condition1 + || condition2 || condition3 +) { +} + +if (condition1) + console.info('bar'); + +if (condition1 + || condition2 + || condition3 +) + console.info('bar'); + + +if (condition1 + || condition2 || condition3 +) + console.info('bar'); + +if (!a(post) + && (!a(context.header) + ^ a(context.header, 'Content-Type')) +) { +// ... +} + +if (foo) { + console.info('bar'); +} + +// Should be no errors even though lines are +// not exactly aligned together. Multi-line function +// call takes precedence. +if (array_key_exists(key, value) + && foo.bar.baz( + key, value2 + ) +) { +} + +if (true) { + foo = true; +}; + +if (foo == 401 // comment + || bar == 3200 /* long comment + here + */ +) { + return false; +} + +if (foo == 401 // comment + || bar == 3200 // long comment here +) { + return false; +} + +if (IPP.errorCode() == 401 + // Comment explaining the next condition here. + || IPP.errorCode() == 3200 +) { + return false; +} + +function bar() { + if (a + && b + ) { + return false; + } +} + +if (a + && foo( + 'a', + 'b' + ) +) { + return false; +} + + + + + + + + + + + + + +if (foo == 401 // phpcs:ignore Standard.Category.Sniff -- for reasons. + || bar == 3200 /* + phpcs:ignore Standard.Category.Sniff -- for reasons. + */ +) { + return false; +} + +if (foo == 401 // phpcs:disable Standard.Category.Sniff -- for reasons. + || bar == 3200 // phpcs:enable +) { + return false; +} + +if (IPP.errorCode() == 401 + // phpcs:ignore Standard.Category.Sniff -- for reasons. + || IPP.errorCode() == 3200 +) { + return false; +} + + if (foo == 401 + /* + * phpcs:disable Standard.Category.Sniff -- for reasons. + */ + || bar == 3200 + ) { + return false; + } + +if (IPP.errorCode() == 401 + || IPP.errorCode() == 3200 + // phpcs:ignore Standard.Category.Sniff -- for reasons. +) { + return false; +} + +if (foo == 401 + || bar == 'someverylongexpectedoutput' +) { + return false; +} + +if (IPP.errorCode() == 401 + || bar + // A comment. + == 'someverylongexpectedoutput' +) { + return false; +} + +if (foo == 401 + || IPP.errorCode() + // phpcs:ignore Standard.Category.Sniff -- for reasons. + == 'someverylongexpectedoutput' +) { + return false; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.php new file mode 100644 index 0000000..aadaea9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/ControlStructures/MultiLineConditionUnitTest.php @@ -0,0 +1,96 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MultiLineCondition sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\ControlStructures\MultiLineConditionSniff + */ +class MultiLineConditionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + $errors = [ + 21 => 1, + 22 => 1, + 35 => 1, + 40 => 1, + 41 => 1, + 42 => 1, + 43 => 1, + 49 => 1, + 54 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 61 => 1, + 67 => 1, + 87 => 1, + 88 => 1, + 89 => 1, + 90 => 1, + 96 => 2, + 101 => 1, + 109 => 2, + 125 => 1, + 145 => 2, + 153 => 2, + 168 => 1, + 177 => 1, + 194 => 2, + 202 => 2, + 215 => 1, + 218 => 2, + 232 => 2, + 239 => 1, + 240 => 2, + 248 => 2, + ]; + + if ($testFile === 'MultiLineConditionUnitTest.inc') { + $errors[183] = 1; + } + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Files/IncludingFileUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Files/IncludingFileUnitTest.inc new file mode 100644 index 0000000..dadfe92 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Files/IncludingFileUnitTest.inc @@ -0,0 +1,99 @@ + +
+Some content goes here.
+
+
+ +
+    Some content goes here.
+    
+    
+ +
+Some content goes here.
+
+
+ +
+    Some content goes here.
+    
+    
+ + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the IncludingFile sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Files\IncludingFileSniff + */ +class IncludingFileUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 5 => 1, + 11 => 1, + 12 => 1, + 16 => 1, + 17 => 1, + 33 => 1, + 34 => 1, + 47 => 1, + 48 => 1, + 64 => 1, + 65 => 1, + 73 => 1, + 74 => 1, + 85 => 1, + 86 => 1, + 98 => 1, + 99 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.inc new file mode 100644 index 0000000..fc6aea0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.inc @@ -0,0 +1,22 @@ +additionalHeaderData[$this->strApplicationName] + = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax')); + +$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName] + = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax')); + +$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName] = + $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax')); + +$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName] + = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax')); +$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName] = 'boo'; + +$var='string'; + +function getInstalledStandards( + $includeGeneric=false, + $standardsDir='' +) { +} +?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php new file mode 100644 index 0000000..d817996 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Formatting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MultiLineAssignment sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Formatting\MultiLineAssignmentSniff + */ +class MultiLineAssignmentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 6 => 1, + 8 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc new file mode 100644 index 0000000..fddd3cb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc @@ -0,0 +1,576 @@ +getFoo() + ->doBar( + $this->getX() // no comma here + ->doY() // this is still the first method argument + ->doZ() // this is still the first method argument + ); +} + +$var = myFunction( +$foo, +$bar +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false + +fputs( + STDOUT, + "Examples: + $ {$app} , --all + $ {$app} --all", $something +); + +$array = array(); +array_map( + function($x) + { + return trim($x, $y); + }, $foo, + $array +); + +$bar = new stdClass( + 4, /* thanks */ 5, /* PSR-2 */ 6 +); + +function doSomething() +{ + return $this->getFoo() + ->doBar( + $this->getX() // no comma here + ->doY() // this is still the first method argument + ->doZ() // this is still the first method argument + ); +} + +doError( + 404, // status code + 'Not Found', // error name + 'Check your id' // fix +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +// Don't report errors for closing braces. Leave that to other sniffs. +foo( + [ + 'this', + 'is', + 'an', + 'array' + ], +[ + 'this', + 'is', + 'an', + 'array' + ], + array( + 'this', + 'is', +'an', +'array' + ), + array( + 'this', + 'is', + 'an', + 'array' + ), + function($x) + { + echo 'wee'; + + return trim($x); + } +); + +function foo() +{ + myFunction( + 'string'. + // comment + // comment + 'string'. + /* comment + * comment + */ + 'string' + ); +} + +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 1 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 1 +test($arg, $arg2); +test( $arg, $arg2 ); +test( $arg, $arg2 ); +test(); +test( ); +test( ); +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 0 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 0 + +?> + + + +
  • + log(// ... + 'error', + sprintf( + 'Message: %s', + isset($e->getData()['object']['evidence_details']) + ? $e->getData()['object']['evidence_details']['due_by'] + : '' + ), + array($e->getData()['object']) +); + +?> +
    + $class + ] + ); ?> +
    + + function ($x) { + return true; + }, + 'baz' => false + ) +); +$qux = array_filter( + $quux, function ($x) { + return $x; + } +); + +array_filter( + [1, 2], + function ($i) : bool { + return $i === 0; + } +); + +foo(array( + 'callback' => function () { + $foo = 'foo'; + return; + }, +)); + +foo( + $a, + /* + $c, + + $d, + */ + $e +); + +test( + 1,2,3,4 + ); + +class Test +{ + public function getInstance() + { + return new static( + 'arg', + 'foo' + ); + } + + public function getSelf() + { + return new self( + 'a','b', 'c' + ); + } +} + +$x = $var('y', +'x'); + +$obj->{$x}(1, + 2); + +return (function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})( + 'a','b' +)('c', + 'd'); + +class Foo +{ + public function bar($a, $b) + { + if (!$a || !$b) { + return; + } + + (new stdClass())->a = $a; + } +} + +return (function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})('a','b')('c','d'); + +function foo() +{ + Bar( + function () { + } + ); +} + +$deprecated_functions = [ + 'the_category_ID' + => function_call( // 7 spaces, not 8. This is the problem line. + $a, + $b + ), +]; + +$deprecated_functions = [ + 'the_category_ID' + => function_call( // 9 spaces, not 8. This is the problem line. + $a, + $b + ), +]; + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false + +printf( + '', + $obj->getName(), // Trailing comment. + $obj->getID(), // phpcs:ignore Standard.Category.SniffName -- for reasons. + $option +); + +// Handling of PHP 7.3 trailing comma's. +functionCall($args, $foo,); +functionCall( + $args, $foo, +); +functionCall( + $args, + $foo, +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +$this->foo( + + ['a','b'], + true + +); + +$this->foo( + + // Comment + ['a','b'], + true + +); + +function m() +{ + $t = ' + ' . (empty(true) ? ' + ' . f( + '1', + '2', + ) . ' + ' : ''); +} + +class C +{ + + public function m() + { + $a = []; + $t = + "SELECT * FROM t +WHERE f IN(" . implode( + ",", + $a + ) . ")"; + } +} + +$notices = array( + 'index' => sprintf( + translation_function('a text string with %s placeholder'), + 'replacement' + ), +); + +$componentType = $this->componentTypeRepository->findByType($this->identifier) ?: + $this->componentTypeFactory->createForType( + $this->identifier, + $this->className, + true, + $this->isPrototypal + ); + +return [ + 'export-path' => 'exports/database/' + . env( + 'APP_CUSTOMER', + 'not-configured' + ) + . '/' . env( + 'APP_IDENTIFIER', + 'not-configured' + ), +]; + +$methods .= + str_replace( + array_keys($replacements), + array_values($replacements), + $methodTemplate + ) + . PHP_EOL . PHP_EOL . str_repeat(' ', 4); + +$rangeValues['min'] = + $this->adjustLowerThreshold( + $this->normalizeRatingForFilter($rangeValues['min']) + ); + +$salesOrderThresholdTransfer->fromArray($salesOrderThresholdEntity->toArray(), true) + ->setSalesOrderThresholdValue( + $this->mapSalesOrderThresholdValueTransfer($salesOrderThresholdTransfer, $salesOrderThresholdEntity) + )->setCurrency( + (new CurrencyTransfer())->fromArray($salesOrderThresholdEntity->getCurrency()->toArray(), true) + )->setStore( + (new StoreTransfer())->fromArray($salesOrderThresholdEntity->getStore()->toArray(), true) + ); + +return trim(preg_replace_callback( + // sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) + // /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ + sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), + function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; + }, + $search + )); + +$a = ['a' => function ($b) { return $b; }]; +$a['a']( 1 ); + +// PHP 8.0 named parameters. +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); + +array_fill_keys( + keys: range( 1, + 12, + ), value: true, +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false +array_fill_keys( + keys: range( 1, + 12, + ), value: true, +); +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +?> +
    +

    +
    +
    +

    +
    + +content +

    + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc.fixed new file mode 100644 index 0000000..1c52523 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.inc.fixed @@ -0,0 +1,591 @@ +getFoo() + ->doBar( + $this->getX() // no comma here + ->doY() // this is still the first method argument + ->doZ() // this is still the first method argument + ); +} + +$var = myFunction( + $foo, + $bar +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false + +fputs( + STDOUT, + "Examples: + $ {$app} , --all + $ {$app} --all", + $something +); + +$array = array(); +array_map( + function($x) + { + return trim($x, $y); + }, + $foo, + $array +); + +$bar = new stdClass( + 4, /* thanks */ + 5, /* PSR-2 */ + 6 +); + +function doSomething() +{ + return $this->getFoo() + ->doBar( + $this->getX() // no comma here + ->doY() // this is still the first method argument + ->doZ() // this is still the first method argument + ); +} + +doError( + 404, // status code + 'Not Found', // error name + 'Check your id' // fix +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +// Don't report errors for closing braces. Leave that to other sniffs. +foo( + [ + 'this', + 'is', + 'an', + 'array' + ], + [ + 'this', + 'is', + 'an', + 'array' + ], + array( + 'this', + 'is', + 'an', + 'array' + ), + array( + 'this', + 'is', + 'an', + 'array' + ), + function($x) + { + echo 'wee'; + + return trim($x); + } +); + +function foo() +{ + myFunction( + 'string'. + // comment + // comment + 'string'. + /* comment + * comment + */ + 'string' + ); +} + +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 1 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 1 +test( $arg, $arg2 ); +test( $arg, $arg2 ); +test( $arg, $arg2 ); +test(); +test(); +test(); +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 0 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 0 + +?> + + + +
  • + log(// ... + 'error', + sprintf( + 'Message: %s', + isset($e->getData()['object']['evidence_details']) + ? $e->getData()['object']['evidence_details']['due_by'] + : '' + ), + array($e->getData()['object']) +); + +?> +
    + $class + ] + ); ?> +
    + + function ($x) { + return true; + }, + 'baz' => false + ) +); +$qux = array_filter( + $quux, function ($x) { + return $x; + } +); + +array_filter( + [1, 2], + function ($i) : bool { + return $i === 0; + } +); + +foo( + array( + 'callback' => function () { + $foo = 'foo'; + return; + }, + ) +); + +foo( + $a, + /* + $c, + + $d, + */ + $e +); + +test( + 1,2,3,4 +); + +class Test +{ + public function getInstance() + { + return new static( + 'arg', + 'foo' + ); + } + + public function getSelf() + { + return new self( + 'a','b', 'c' + ); + } +} + +$x = $var( + 'y', + 'x' +); + +$obj->{$x}( + 1, + 2 +); + +return (function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})( + 'a','b' +)( + 'c', + 'd' +); + +class Foo +{ + public function bar($a, $b) + { + if (!$a || !$b) { + return; + } + + (new stdClass())->a = $a; + } +} + +return (function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})('a','b')('c','d'); + +function foo() +{ + Bar( + function () { + } + ); +} + +$deprecated_functions = [ + 'the_category_ID' + => function_call( // 7 spaces, not 8. This is the problem line. + $a, + $b + ), +]; + +$deprecated_functions = [ + 'the_category_ID' + => function_call( // 9 spaces, not 8. This is the problem line. + $a, + $b + ), +]; + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false + +printf( + '', + $obj->getName(), // Trailing comment. + $obj->getID(), // phpcs:ignore Standard.Category.SniffName -- for reasons. + $option +); + +// Handling of PHP 7.3 trailing comma's. +functionCall($args, $foo,); +functionCall( + $args, + $foo, +); +functionCall( + $args, + $foo, +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +$this->foo( + ['a','b'], + true +); + +$this->foo( + // Comment + ['a','b'], + true +); + +function m() +{ + $t = ' + ' . (empty(true) ? ' + ' . f( + '1', + '2', + ) . ' + ' : ''); +} + +class C +{ + + public function m() + { + $a = []; + $t = + "SELECT * FROM t +WHERE f IN(" . implode( + ",", + $a + ) . ")"; + } +} + +$notices = array( + 'index' => sprintf( + translation_function('a text string with %s placeholder'), + 'replacement' + ), +); + +$componentType = $this->componentTypeRepository->findByType($this->identifier) ?: + $this->componentTypeFactory->createForType( + $this->identifier, + $this->className, + true, + $this->isPrototypal + ); + +return [ + 'export-path' => 'exports/database/' + . env( + 'APP_CUSTOMER', + 'not-configured' + ) + . '/' . env( + 'APP_IDENTIFIER', + 'not-configured' + ), +]; + +$methods .= + str_replace( + array_keys($replacements), + array_values($replacements), + $methodTemplate + ) + . PHP_EOL . PHP_EOL . str_repeat(' ', 4); + +$rangeValues['min'] = + $this->adjustLowerThreshold( + $this->normalizeRatingForFilter($rangeValues['min']) + ); + +$salesOrderThresholdTransfer->fromArray($salesOrderThresholdEntity->toArray(), true) + ->setSalesOrderThresholdValue( + $this->mapSalesOrderThresholdValueTransfer($salesOrderThresholdTransfer, $salesOrderThresholdEntity) + )->setCurrency( + (new CurrencyTransfer())->fromArray($salesOrderThresholdEntity->getCurrency()->toArray(), true) + )->setStore( + (new StoreTransfer())->fromArray($salesOrderThresholdEntity->getStore()->toArray(), true) + ); + +return trim( + preg_replace_callback( + // sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) + // /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ + sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), + function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; + }, + $search + ) +); + +$a = ['a' => function ($b) { return $b; }]; +$a['a'](1); + +// PHP 8.0 named parameters. +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); + +array_fill_keys( + keys: range( + 1, + 12, + ), value: true, +); + +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments false +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); +// phpcs:set PEAR.Functions.FunctionCallSignature allowMultipleArguments true + +?> +
    +

    +
    +
    +

    +
    + +content +

    + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js new file mode 100644 index 0000000..5e77e57 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js @@ -0,0 +1,80 @@ +test( +); +test(); +test(arg, arg2); +test (); +test( ); +test() ; +test( arg); +test( arg ); +test ( arg ); + +if (foo(arg) === true) { + +} + +var something = get(arg1, arg2); +var something = get(arg1, arg2) ; +var something = get(arg1, arg2) ; + +make_foo(string/*the string*/, true/*test*/); +make_foo(string/*the string*/, true/*test*/ ); +make_foo(string /*the string*/, true /*test*/); +make_foo(/*the string*/string, /*test*/true); +make_foo( /*the string*/string, /*test*/true); + +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 1 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 1 +test(arg, arg2); +test( arg, arg2 ); +test( arg, arg2 ); +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 0 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 0 + +this.init = function(data) { + a.b('').a(function(itemid, target) { + b( + itemid, + target, + { + reviewData: _reviewData, + pageid: itemid + }, + '', + function() { + var _showAspectItems = function(itemid) { + a.a(a.c(''), ''); + a.b(a.c('-' + itemid), ''); + }; + a.foo(function(itemid, target) { + _foo(itemid); + }); + } + ); + }); +}; + +a.prototype = { + + a: function() + { + this.addItem( + { + /** + * @return void + */ + a: function() + { + + }, + /** + * @return void + */ + a: function() + { + + }, + } + ); + } +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js.fixed new file mode 100644 index 0000000..7855ac6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.js.fixed @@ -0,0 +1,84 @@ +test( +); +test(); +test(arg, arg2); +test(); +test(); +test(); +test(arg); +test(arg); +test(arg); + +if (foo(arg) === true) { + +} + +var something = get(arg1, arg2); +var something = get(arg1, arg2); +var something = get(arg1, arg2); + +make_foo(string/*the string*/, true/*test*/); +make_foo(string/*the string*/, true/*test*/); +make_foo(string /*the string*/, true /*test*/); +make_foo(/*the string*/string, /*test*/true); +make_foo(/*the string*/string, /*test*/true); + +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 1 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 1 +test( arg, arg2 ); +test( arg, arg2 ); +test( arg, arg2 ); +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesAfterOpen 0 +// phpcs:set PEAR.Functions.FunctionCallSignature requiredSpacesBeforeClose 0 + +this.init = function(data) { + a.b('').a( + function(itemid, target) { + b( + itemid, + target, + { + reviewData: _reviewData, + pageid: itemid + }, + '', + function() { + var _showAspectItems = function(itemid) { + a.a(a.c(''), ''); + a.b(a.c('-' + itemid), ''); + }; + a.foo( + function(itemid, target) { + _foo(itemid); + } + ); + } + ); + } + ); +}; + +a.prototype = { + + a: function() + { + this.addItem( + { + /** + * @return void + */ + a: function() + { + + }, + /** + * @return void + */ + a: function() + { + + }, + } + ); + } +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.php new file mode 100644 index 0000000..f6d456a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionCallSignatureUnitTest.php @@ -0,0 +1,164 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionCallSignature sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionCallSignatureSniff + */ +class FunctionCallSignatureUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile === 'FunctionCallSignatureUnitTest.js') { + return [ + 5 => 1, + 6 => 2, + 7 => 1, + 8 => 1, + 9 => 2, + 10 => 3, + 17 => 1, + 18 => 1, + 21 => 1, + 24 => 1, + 28 => 2, + 30 => 2, + 35 => 1, + 49 => 1, + 51 => 1, + 54 => 1, + 70 => 1, + 71 => 1, + ]; + }//end if + + return [ + 5 => 1, + 6 => 2, + 7 => 1, + 8 => 1, + 9 => 2, + 10 => 3, + 17 => 1, + 18 => 1, + 31 => 1, + 34 => 1, + 43 => 2, + 57 => 1, + 59 => 1, + 63 => 1, + 64 => 1, + 82 => 1, + 93 => 1, + 100 => 1, + 106 => 2, + 119 => 1, + 120 => 1, + 129 => 1, + 137 => 1, + 142 => 2, + 171 => 1, + 180 => 1, + 181 => 1, + 194 => 1, + 213 => 2, + 215 => 2, + 217 => 2, + 218 => 2, + 277 => 1, + 278 => 1, + 303 => 1, + 308 => 1, + 321 => 1, + 322 => 1, + 329 => 1, + 330 => 1, + 337 => 1, + 342 => 1, + 343 => 1, + 345 => 1, + 346 => 2, + 353 => 1, + 354 => 1, + 355 => 2, + 377 => 1, + 378 => 1, + 379 => 1, + 380 => 1, + 385 => 1, + 386 => 1, + 387 => 1, + 388 => 1, + 393 => 1, + 394 => 1, + 395 => 1, + 396 => 1, + 411 => 1, + 422 => 1, + 424 => 1, + 429 => 1, + 432 => 1, + 440 => 1, + 441 => 1, + 442 => 1, + 464 => 1, + 510 => 1, + 513 => 1, + 514 => 1, + 523 => 1, + 524 => 3, + 527 => 2, + 539 => 1, + 540 => 1, + 546 => 1, + 547 => 1, + 548 => 1, + 559 => 1, + 567 => 1, + 568 => 1, + 573 => 1, + 574 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionDeclarationUnitTest.inc new file mode 100644 index 0000000..6ba3bd9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/FunctionDeclarationUnitTest.inc @@ -0,0 +1,490 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionDeclarationSniff + */ +class FunctionDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile === 'FunctionDeclarationUnitTest.inc') { + $errors = [ + 3 => 1, + 4 => 1, + 5 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 14 => 1, + 17 => 1, + 44 => 1, + 52 => 1, + 61 => 2, + 98 => 1, + 110 => 2, + 120 => 3, + 121 => 1, + 140 => 1, + 145 => 1, + 161 => 2, + 162 => 2, + 164 => 2, + 167 => 2, + 171 => 1, + 173 => 1, + 201 => 1, + 206 => 1, + 208 => 1, + 216 => 1, + 223 => 1, + 230 => 1, + 237 => 1, + 243 => 1, + 247 => 1, + 251 => 2, + 253 => 2, + 257 => 2, + 259 => 1, + 263 => 1, + 265 => 1, + 269 => 1, + 273 => 1, + 277 => 1, + 278 => 1, + 283 => 1, + 287 => 2, + 289 => 2, + 293 => 2, + 295 => 1, + 299 => 1, + 301 => 1, + 305 => 1, + 309 => 1, + 313 => 1, + 314 => 1, + 350 => 1, + 351 => 1, + 352 => 1, + 353 => 1, + 361 => 1, + 362 => 1, + 363 => 1, + 364 => 1, + 365 => 1, + 366 => 1, + 367 => 1, + 368 => 1, + 369 => 1, + 370 => 1, + 371 => 1, + 402 => 1, + 406 => 1, + 475 => 1, + 483 => 1, + 490 => 2, + ]; + } else { + $errors = [ + 3 => 1, + 4 => 1, + 5 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 14 => 1, + 17 => 1, + 41 => 1, + 48 => 1, + ]; + }//end if + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.inc new file mode 100644 index 0000000..8f8d64a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.inc @@ -0,0 +1,119 @@ + $a[] = $b; + +class OnlyConstructorPropertyPromotion { + public function __construct( + public string $name = '', + protected $bar + ) {} +} + +class ConstructorPropertyPromotionMixedWithNormalParams { + public function __construct( + public string $name = '', + ?int $optionalParam = 0, + mixed $requiredParam, + ) {} +} + +// Intentional syntax error. Must be last thing in the file. +function diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.php new file mode 100644 index 0000000..5c2450b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/Functions/ValidDefaultValueUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidDefaultValue sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\ValidDefaultValueSniff + */ +class ValidDefaultValueUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 29 => 1, + 34 => 1, + 39 => 1, + 71 => 1, + 76 => 1, + 81 => 1, + 91 => 1, + 99 => 1, + 101 => 1, + 106 => 1, + 114 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidClassNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidClassNameUnitTest.inc new file mode 100644 index 0000000..053a4fe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidClassNameUnitTest.inc @@ -0,0 +1,90 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidClassName sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions\ValidClassNameSniff + */ +class ValidClassNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 7 => 2, + 9 => 1, + 19 => 1, + 24 => 1, + 26 => 2, + 28 => 1, + 38 => 1, + 40 => 2, + 42 => 2, + 44 => 1, + 46 => 1, + 50 => 1, + 52 => 2, + 54 => 1, + 64 => 1, + 66 => 2, + 68 => 1, + 72 => 1, + 74 => 2, + 76 => 1, + 86 => 1, + 88 => 2, + 90 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidFunctionNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidFunctionNameUnitTest.inc new file mode 100644 index 0000000..18b1a48 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidFunctionNameUnitTest.inc @@ -0,0 +1,243 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidFunctionName sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions\ValidFunctionNameSniff + */ +class ValidFunctionNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 11 => 1, + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + 16 => 1, + 17 => 2, + 18 => 2, + 19 => 2, + 20 => 2, + 24 => 1, + 25 => 1, + 26 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 2, + 31 => 2, + 32 => 2, + 33 => 2, + 35 => 1, + 36 => 1, + 37 => 2, + 38 => 2, + 39 => 2, + 40 => 2, + 43 => 1, + 44 => 1, + 45 => 1, + 46 => 1, + 50 => 1, + 51 => 1, + 52 => 1, + 53 => 1, + 56 => 1, + 57 => 1, + 58 => 1, + 59 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + 73 => 2, + 74 => 2, + 75 => 2, + 76 => 2, + 80 => 1, + 81 => 1, + 82 => 1, + 83 => 1, + 86 => 1, + 87 => 1, + 88 => 1, + 89 => 1, + 95 => 1, + 96 => 1, + 97 => 1, + 98 => 1, + 99 => 1, + 100 => 1, + 101 => 2, + 102 => 2, + 103 => 2, + 104 => 2, + 123 => 1, + 125 => 1, + 126 => 2, + 129 => 1, + 130 => 1, + 131 => 1, + 132 => 1, + 133 => 1, + 134 => 1, + 135 => 1, + 136 => 1, + 137 => 1, + 138 => 1, + 139 => 1, + 140 => 3, + 141 => 1, + 143 => 1, + 144 => 1, + 145 => 3, + 147 => 2, + 148 => 1, + 149 => 1, + 181 => 1, + 201 => 1, + 203 => 1, + 204 => 2, + 207 => 2, + 212 => 1, + 213 => 1, + 214 => 1, + 235 => 1, + 236 => 2, + 239 => 1, + 242 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.inc new file mode 100644 index 0000000..3c03da3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -0,0 +1,101 @@ +def["POP_{$cc}_A"]}' + and POP_{$cc}_B = +'{$this->def["POP_{$cc}_B"]}')"; + } +} + +class mpgResponse{ + var $term_id; + var $currentTag; + function characterHandler($parser,$data){ + switch($this->currentTag) + { + case "term_id": { + $this->term_id=$data; + break; + } + } + }//end characterHandler +}//end class mpgResponse + +class foo +{ + const bar = <<setLogger( + new class { + private $varName = 'hello'; + private $_varName = 'hello'; +}); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.php new file mode 100644 index 0000000..5b3e58f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidVariableName sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions\ValidVariableNameSniff + */ +class ValidVariableNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 12 => 1, + 17 => 1, + 22 => 1, + 92 => 1, + 93 => 1, + 94 => 1, + 99 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc new file mode 100644 index 0000000..b1b09d9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc @@ -0,0 +1,142 @@ +someFunction("some", "parameter") +->someOtherFunc(23, 42)-> + someOtherFunc2($one, $two) + + ->someOtherFunc3(23, 42) + ->andAThirdFunction(); + + $someObject->someFunction("some", "parameter") + ->someOtherFunc(23, 42); + +$someObject->someFunction("some", "parameter")->someOtherFunc(23, 42); + +$someObject->someFunction("some", "parameter") + ->someOtherFunc(23, 42); + +func( + $bar->foo() +) + ->bar(); + +func( + $bar->foo() +) + ->bar( + $bar->foo() + ->bar() + ->func() + ); + +$object + ->setBar($foo) + ->setFoo($bar); + +if ($bar) { + $object + ->setBar($foo) + ->setFoo($bar); +} + +$response -> CompletedTrackDetails -> TrackDetails -> Events; +$response + -> CompletedTrackDetails + -> TrackDetails + -> Events; + +$response + -> CompletedTrackDetails +-> TrackDetails + -> Events; + +$var = get_object( + $foo->something() + ->query() +)->two() + ->three(); + +$foo->one( + $foo + ->two() +); + +get_object()->one() + ->two() + ->three(); + +someclass::one() + ->two() + ->three(); + +(new someclass())->one() + ->two() + ->three(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel true + +$someObject + ->startSomething() + ->someOtherFunc(23, 42) +->endSomething() +->doSomething(23, 42) +->endEverything(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() +->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel false + +$object + ?->setBar($foo) + ?->setFoo($bar); + +$someObject?->someFunction("some", "parameter") +->someOtherFunc(23, 42)?-> + someOtherFunc2($one, $two) + +->someOtherFunc3(23, 42) + ?->andAThirdFunction(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel true +$object + ?->setBar($foo) + ?->setFoo($bar); + +$someObject?->someFunction("some", "parameter") +->someOtherFunc(23, 42) + ?->someOtherFunc2($one, $two) + +->someOtherFunc3(23, 42) + ?->andAThirdFunction(); +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel false + +$someObject + ->startSomething(paramName: $value) + ->someOtherFunc(nameA: 23, nameB: 42) +->endSomething($value, name: $value) +->endEverything(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc.fixed new file mode 100644 index 0000000..5d5b77b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.inc.fixed @@ -0,0 +1,142 @@ +someFunction("some", "parameter") + ->someOtherFunc(23, 42) + ->someOtherFunc2($one, $two) + + ->someOtherFunc3(23, 42) + ->andAThirdFunction(); + + $someObject->someFunction("some", "parameter") + ->someOtherFunc(23, 42); + +$someObject->someFunction("some", "parameter")->someOtherFunc(23, 42); + +$someObject->someFunction("some", "parameter") + ->someOtherFunc(23, 42); + +func( + $bar->foo() +) + ->bar(); + +func( + $bar->foo() +) + ->bar( + $bar->foo() + ->bar() + ->func() + ); + +$object + ->setBar($foo) + ->setFoo($bar); + +if ($bar) { + $object + ->setBar($foo) + ->setFoo($bar); +} + +$response -> CompletedTrackDetails -> TrackDetails -> Events; +$response + -> CompletedTrackDetails + -> TrackDetails + -> Events; + +$response + -> CompletedTrackDetails + -> TrackDetails + -> Events; + +$var = get_object( + $foo->something() + ->query() +)->two() + ->three(); + +$foo->one( + $foo + ->two() +); + +get_object()->one() + ->two() + ->three(); + +someclass::one() + ->two() + ->three(); + +(new someclass())->one() + ->two() + ->three(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel true + +$someObject + ->startSomething() + ->someOtherFunc(23, 42) + ->endSomething() + ->doSomething(23, 42) + ->endEverything(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +$rootNode + ->one() + ->two() + ->three() + ->four() + ->five(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel false + +$object + ?->setBar($foo) + ?->setFoo($bar); + +$someObject?->someFunction("some", "parameter") + ->someOtherFunc(23, 42) + ?->someOtherFunc2($one, $two) + + ->someOtherFunc3(23, 42) + ?->andAThirdFunction(); + +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel true +$object + ?->setBar($foo) + ?->setFoo($bar); + +$someObject?->someFunction("some", "parameter") + ->someOtherFunc(23, 42) + ?->someOtherFunc2($one, $two) + + ->someOtherFunc3(23, 42) + ?->andAThirdFunction(); +// phpcs:set PEAR.WhiteSpace.ObjectOperatorIndent multilevel false + +$someObject + ->startSomething(paramName: $value) + ->someOtherFunc(nameA: 23, nameB: 42) + ->endSomething($value, name: $value) + ->endEverything(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.php new file mode 100644 index 0000000..fa34ed4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ObjectOperatorIndentUnitTest.php @@ -0,0 +1,79 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ObjectOperatorIndent sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ObjectOperatorIndentSniff + */ +class ObjectOperatorIndentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 2, + 6 => 1, + 15 => 1, + 27 => 1, + 37 => 1, + 38 => 1, + 48 => 1, + 49 => 1, + 50 => 1, + 65 => 1, + 69 => 1, + 73 => 1, + 79 => 1, + 80 => 1, + 81 => 1, + 82 => 1, + 95 => 1, + 103 => 1, + 119 => 2, + 122 => 1, + 131 => 1, + 134 => 1, + 140 => 1, + 141 => 1, + 142 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc new file mode 100644 index 0000000..3f90067 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc @@ -0,0 +1,164 @@ +{$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +switch ($foo) { +case 1: + switch ($bar) { + default: + if ($something) { + echo $string{1}; + } else if ($else) { + switch ($else) { + case 1: + // Do something. + break; + default: + // Do something. + break; + } + } + } +break; +case 2: + // Do something; + break; +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + default: + return 'Unknown'; +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + return 'Processing.'; + default: + return 'Unknown'; +} + +switch($i) { +case 1: {} +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + exit; + default: + exit; +} + +if ($foo): + if ($bar): + $foo = 1; + elseif ($baz): + $foo = 2; + endif; +endif; + +if ($foo): +elseif ($baz): $foo = 2; +endif; + +?> +
      + +
    • + +
    +
      + +
    • + +
    +
      + +
    • + +
    + +getSummaryCount(); ?> +
    class="empty"> + + 'a', 2 => 'b' }; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' + }; + +enum Enum +{ +} + +enum Suits {} + +enum Cards +{ + } diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc.fixed new file mode 100644 index 0000000..f369c2b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc.fixed @@ -0,0 +1,170 @@ +{$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +switch ($foo) { +case 1: + switch ($bar) { + default: + if ($something) { + echo $string{1}; + } else if ($else) { + switch ($else) { + case 1: + // Do something. + break; + default: + // Do something. + break; + } + } + } + break; +case 2: + // Do something; + break; +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + default: + return 'Unknown'; +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + return 'Processing.'; + default: + return 'Unknown'; +} + +switch($i) { +case 1: { + } +} + +switch ($httpResponseCode) { + case 100: + case 101: + case 102: + exit; + default: + exit; +} + +if ($foo): + if ($bar): + $foo = 1; + elseif ($baz): + $foo = 2; + endif; +endif; + +if ($foo): +elseif ($baz): $foo = 2; +endif; + +?> +
      + +
    • + +
    +
      + +
    • + +
    +
      + +
    • + +
    + +getSummaryCount(); ?> +
    class="empty"> + + 'a', 2 => 'b' +}; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' +}; + +enum Enum +{ +} + +enum Suits { +} + +enum Cards +{ +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.php new file mode 100644 index 0000000..2683d6b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeClosingBraceUnitTest.php @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ScopeClosingBrace sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ScopeClosingBraceSniff + */ +class ScopeClosingBraceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 11 => 1, + 13 => 1, + 24 => 1, + 30 => 1, + 61 => 1, + 65 => 1, + 85 => 1, + 89 => 1, + 98 => 1, + 122 => 1, + 127 => 1, + 135 => 1, + 141 => 1, + 146 => 1, + 149 => 1, + 154 => 1, + 160 => 1, + 164 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeIndentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeIndentUnitTest.inc new file mode 100644 index 0000000..b122a14 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests/WhiteSpace/ScopeIndentUnitTest.inc @@ -0,0 +1,314 @@ +hello(); // error here + } + + function hello() // error here + { // no error here as brackets can be put anywhere in the pear standard + echo 'hello'; + } + + function hello2() + { + if (TRUE) { // error here + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; // error here + } + + while (TRUE) { + echo 'hello'; // error here + } + + do { // error here + echo 'hello'; // error here + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
    +
    +
    +validate()) {
    +    $safe = $form->getSubmitValues();
    +}
    +?>
    +
    +open(); // error here + } + + public function open() + { + // Some inline stuff that shouldn't error + if (TRUE) echo 'hello'; + foreach ($tokens as $token) echo $token; + } + + /** + * This is a comment 1. + * This is a comment 2. + * This is a comment 3. + * This is a comment 4. + */ + public function close() + { + // All ok. + if (TRUE) { + if (TRUE) { + } else if (FALSE) { + foreach ($tokens as $token) { + switch ($token) { + case '1': + case '2': + if (true) { + if (false) { + if (false) { + if (false) { + echo 'hello'; + } + } + } + } + break; + case '5': + break; + } + do { + while (true) { + foreach ($tokens as $token) { + for ($i = 0; $i < $token; $i++) { + echo 'hello'; + } + } + } + } while (true); + } + } + } + } + + /* + This is another c style comment 1. + This is another c style comment 2. + This is another c style comment 3. + This is another c style comment 4. + This is another c style comment 5. + */ + + /* + * + * + * + */ + + /** + */ + + /* + This comment has a newline in it. + + */ + + public function read() + { + echo 'hello'; + + // no errors below. + $array = array( + 'this', + 'that' => array( + 'hello', + 'hello again' => array( + 'hello', + ), + ), + ); + } +} + +abstract class Test3 +{ + public function parse() + { + + foreach ($t as $ndx => $token) { + if (is_array($token)) { + echo 'here'; + } else { + $ts[] = array("token" => $token, "value" => ''); + + $last = count($ts) - 1; + + switch ($token) { + case '(': + + if ($last >= 3 && + $ts[0]['token'] != T_CLASS && + $ts[$last - 2]['token'] == T_OBJECT_OPERATOR && + $ts[$last - 3]['token'] == T_VARIABLE ) { + + + if (true) { + echo 'hello'; + } + } + array_push($braces, $token); + break; + } + } + } + } +} + +function test() +{ + $o = << + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PEAR\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ScopeIndent sniff. + * + * @covers \PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ScopeIndentSniff + */ +class ScopeIndentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 10 => 1, + 17 => 1, + 20 => 1, + 24 => 1, + 25 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 58 => 1, + 123 => 1, + 224 => 1, + 225 => 1, + 279 => 1, + 284 => 1, + 311 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/ruleset.xml new file mode 100644 index 0000000..1bf94ca --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PEAR/ruleset.xml @@ -0,0 +1,41 @@ + + + The PEAR coding standard. + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Classes/ClassDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Classes/ClassDeclarationStandard.xml new file mode 100644 index 0000000..eaae99b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Classes/ClassDeclarationStandard.xml @@ -0,0 +1,48 @@ + + + + + + + class Bar { +} + ]]> + + + class Bar { +} + +class Baz { +} + ]]> + + + + + namespace Foo; + +class Bar { +} + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Files/SideEffectsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Files/SideEffectsStandard.xml new file mode 100644 index 0000000..0ed04a0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Files/SideEffectsStandard.xml @@ -0,0 +1,27 @@ + + + + + + + + + + echo "Class Foo loaded." + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Methods/CamelCapsMethodNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Methods/CamelCapsMethodNameStandard.xml new file mode 100644 index 0000000..8db899d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Methods/CamelCapsMethodNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + doBar() + { + } +} + ]]> + + + do_bar() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Classes/ClassDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Classes/ClassDeclarationSniff.php new file mode 100644 index 0000000..e3f626b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Classes/ClassDeclarationSniff.php @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClassDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param integer $stackPtr The position of the current token in + * the token stack. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $errorData = [strtolower($tokens[$stackPtr]['content'])]; + + $nextClass = $phpcsFile->findNext([T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], ($tokens[$stackPtr]['scope_closer'] + 1)); + if ($nextClass !== false) { + $error = 'Each %s must be in a file by itself'; + $phpcsFile->addError($error, $nextClass, 'MultipleClasses', $errorData); + $phpcsFile->recordMetric($stackPtr, 'One class per file', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'One class per file', 'yes'); + } + + $namespace = $phpcsFile->findNext([T_NAMESPACE, T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], 0); + if ($tokens[$namespace]['code'] !== T_NAMESPACE) { + $error = 'Each %s must be in a namespace of at least one level (a top-level vendor name)'; + $phpcsFile->addError($error, $stackPtr, 'MissingNamespace', $errorData); + $phpcsFile->recordMetric($stackPtr, 'Class defined in namespace', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Class defined in namespace', 'yes'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Files/SideEffectsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Files/SideEffectsSniff.php new file mode 100644 index 0000000..5f22b1f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Files/SideEffectsSniff.php @@ -0,0 +1,303 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SideEffectsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the token stack. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $result = $this->searchForConflict($phpcsFile, 0, ($phpcsFile->numTokens - 1), $tokens); + + if ($result['symbol'] !== null && $result['effect'] !== null) { + $error = 'A file should declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it should execute logic with side effects, but should not do both. The first symbol is defined on line %s and the first side effect is on line %s.'; + $data = [ + $tokens[$result['symbol']]['line'], + $tokens[$result['effect']]['line'], + ]; + $phpcsFile->addWarning($error, 0, 'FoundWithSymbols', $data); + $phpcsFile->recordMetric($stackPtr, 'Declarations and side effects mixed', 'yes'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Declarations and side effects mixed', 'no'); + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + + /** + * Searches for symbol declarations and side effects. + * + * Returns the positions of both the first symbol declared and the first + * side effect in the file. A NULL value for either indicates nothing was + * found. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $start The token to start searching from. + * @param int $end The token to search to. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return array + */ + private function searchForConflict($phpcsFile, $start, $end, $tokens) + { + $symbols = [ + T_CLASS => T_CLASS, + T_INTERFACE => T_INTERFACE, + T_TRAIT => T_TRAIT, + T_ENUM => T_ENUM, + T_FUNCTION => T_FUNCTION, + ]; + + $conditions = [ + T_IF => T_IF, + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + ]; + + $checkAnnotations = $phpcsFile->config->annotations; + + $firstSymbol = null; + $firstEffect = null; + for ($i = $start; $i <= $end; $i++) { + // Respect phpcs:disable comments. + if ($checkAnnotations === true + && $tokens[$i]['code'] === T_PHPCS_DISABLE + && (empty($tokens[$i]['sniffCodes']) === true + || isset($tokens[$i]['sniffCodes']['PSR1']) === true + || isset($tokens[$i]['sniffCodes']['PSR1.Files']) === true + || isset($tokens[$i]['sniffCodes']['PSR1.Files.SideEffects']) === true + || isset($tokens[$i]['sniffCodes']['PSR1.Files.SideEffects.FoundWithSymbols']) === true) + ) { + do { + $i = $phpcsFile->findNext(T_PHPCS_ENABLE, ($i + 1)); + } while ($i !== false + && empty($tokens[$i]['sniffCodes']) === false + && isset($tokens[$i]['sniffCodes']['PSR1']) === false + && isset($tokens[$i]['sniffCodes']['PSR1.Files']) === false + && isset($tokens[$i]['sniffCodes']['PSR1.Files.SideEffects']) === false + && isset($tokens[$i]['sniffCodes']['PSR1.Files.SideEffects.FoundWithSymbols']) === false); + + if ($i === false) { + // The entire rest of the file is disabled, + // so return what we have so far. + break; + } + + continue; + } + + // Ignore whitespace and comments. + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) { + continue; + } + + // Ignore PHP tags. + if ($tokens[$i]['code'] === T_OPEN_TAG + || $tokens[$i]['code'] === T_CLOSE_TAG + ) { + continue; + } + + // Ignore shebang. + if (substr($tokens[$i]['content'], 0, 2) === '#!') { + continue; + } + + // Ignore logical operators. + if (isset(Tokens::$booleanOperators[$tokens[$i]['code']]) === true) { + continue; + } + + // Ignore entire namespace, declare, const and use statements. + if ($tokens[$i]['code'] === T_NAMESPACE + || $tokens[$i]['code'] === T_USE + || $tokens[$i]['code'] === T_DECLARE + || $tokens[$i]['code'] === T_CONST + ) { + if (isset($tokens[$i]['scope_opener']) === true) { + $i = $tokens[$i]['scope_closer']; + if ($tokens[$i]['code'] === T_ENDDECLARE) { + $semicolon = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), null, true); + if ($semicolon !== false && $tokens[$semicolon]['code'] === T_SEMICOLON) { + $i = $semicolon; + } + } + } else { + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($i + 1)); + if ($semicolon !== false) { + $i = $semicolon; + } + } + + continue; + } + + // Ignore function/class prefixes. + if (isset(Tokens::$methodPrefixes[$tokens[$i]['code']]) === true + || $tokens[$i]['code'] === T_READONLY + ) { + continue; + } + + // Ignore anon classes. + if ($tokens[$i]['code'] === T_ANON_CLASS) { + $i = $tokens[$i]['scope_closer']; + continue; + } + + // Ignore attributes. + if ($tokens[$i]['code'] === T_ATTRIBUTE + && isset($tokens[$i]['attribute_closer']) === true + ) { + $i = $tokens[$i]['attribute_closer']; + continue; + } + + // Detect and skip over symbols. + if (isset($symbols[$tokens[$i]['code']]) === true + && isset($tokens[$i]['scope_closer']) === true + ) { + if ($firstSymbol === null) { + $firstSymbol = $i; + } + + $i = $tokens[$i]['scope_closer']; + continue; + } else if ($tokens[$i]['code'] === T_STRING + && strtolower($tokens[$i]['content']) === 'define' + ) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), null, true); + if ($tokens[$prev]['code'] !== T_OBJECT_OPERATOR + && $tokens[$prev]['code'] !== T_NULLSAFE_OBJECT_OPERATOR + && $tokens[$prev]['code'] !== T_DOUBLE_COLON + && $tokens[$prev]['code'] !== T_FUNCTION + ) { + if ($firstSymbol === null) { + $firstSymbol = $i; + } + + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($i + 1)); + if ($semicolon !== false) { + $i = $semicolon; + } + + continue; + } + }//end if + + // Special case for defined() as it can be used to see + // if a constant (a symbol) should be defined or not and + // doesn't need to use a full conditional block. + if ($tokens[$i]['code'] === T_STRING + && strtolower($tokens[$i]['content']) === 'defined' + ) { + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), null, true); + if ($openBracket !== false + && $tokens[$openBracket]['code'] === T_OPEN_PARENTHESIS + && isset($tokens[$openBracket]['parenthesis_closer']) === true + ) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), null, true); + if ($tokens[$prev]['code'] !== T_OBJECT_OPERATOR + && $tokens[$prev]['code'] !== T_NULLSAFE_OBJECT_OPERATOR + && $tokens[$prev]['code'] !== T_DOUBLE_COLON + && $tokens[$prev]['code'] !== T_FUNCTION + ) { + $i = $tokens[$openBracket]['parenthesis_closer']; + continue; + } + } + }//end if + + // Conditional statements are allowed in symbol files as long as the + // contents is only a symbol definition. So don't count these as effects + // in this case. + if (isset($conditions[$tokens[$i]['code']]) === true) { + if (isset($tokens[$i]['scope_opener']) === false) { + // Probably an "else if", so just ignore. + continue; + } + + $result = $this->searchForConflict( + $phpcsFile, + ($tokens[$i]['scope_opener'] + 1), + ($tokens[$i]['scope_closer'] - 1), + $tokens + ); + + if ($result['symbol'] !== null) { + if ($firstSymbol === null) { + $firstSymbol = $result['symbol']; + } + + if ($result['effect'] !== null) { + // Found a conflict. + $firstEffect = $result['effect']; + break; + } + } + + if ($firstEffect === null) { + $firstEffect = $result['effect']; + } + + $i = $tokens[$i]['scope_closer']; + continue; + }//end if + + if ($firstEffect === null) { + $firstEffect = $i; + } + + if ($firstSymbol !== null) { + // We have a conflict we have to report, so no point continuing. + break; + } + }//end for + + return [ + 'symbol' => $firstSymbol, + 'effect' => $firstEffect, + ]; + + }//end searchForConflict() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Methods/CamelCapsMethodNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Methods/CamelCapsMethodNameSniff.php new file mode 100644 index 0000000..0cf1022 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Methods/CamelCapsMethodNameSniff.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Sniffs\Methods; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff as GenericCamelCapsFunctionNameSniff; +use PHP_CodeSniffer\Util\Common; + +class CamelCapsMethodNameSniff extends GenericCamelCapsFunctionNameSniff +{ + + + /** + * Processes the tokens within the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * @param int $currScope The position of the current scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + + // Ignore magic methods. + if (preg_match('|^__[^_]|', $methodName) !== 0) { + $magicPart = strtolower(substr($methodName, 2)); + if (isset($this->magicMethods[$magicPart]) === true + || isset($this->methodsDoubleUnderscore[$magicPart]) === true + ) { + return; + } + } + + $testName = ltrim($methodName, '_'); + if ($testName !== '' && Common::isCamelCaps($testName, false, true, false) === false) { + $error = 'Method name "%s" is not in camel caps format'; + $className = $phpcsFile->getDeclarationName($currScope); + if (isset($className) === false) { + $className = '[Anonymous Class]'; + } + + $errorData = [$className.'::'.$methodName]; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'yes'); + } + + }//end processTokenWithinScope() + + + /** + * Processes the tokens outside the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Classes/ClassDeclarationUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Classes/ClassDeclarationUnitTest.1.inc new file mode 100644 index 0000000..58cb85e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Classes/ClassDeclarationUnitTest.1.inc @@ -0,0 +1,3 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR1\Sniffs\Classes\ClassDeclarationSniff + */ +class ClassDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile === 'ClassDeclarationUnitTest.2.inc') { + return []; + } + + return [ + 2 => 1, + 3 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.1.inc new file mode 100644 index 0000000..b7e1dc9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.1.inc @@ -0,0 +1,87 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.10.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.10.inc new file mode 100644 index 0000000..63f256d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.10.inc @@ -0,0 +1,8 @@ +define("MAXSIZE", 100); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.14.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.14.inc new file mode 100644 index 0000000..9499885 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.14.inc @@ -0,0 +1,2 @@ +define("MAXSIZE", 100); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.15.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.15.inc new file mode 100644 index 0000000..0500d10 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.15.inc @@ -0,0 +1,2 @@ +defined('MINSIZE') or define("MAXSIZE", 100); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.16.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.16.inc new file mode 100644 index 0000000..588ece5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.16.inc @@ -0,0 +1,2 @@ +defined('MINSIZE') or define("MAXSIZE", 100); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.17.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.17.inc new file mode 100644 index 0000000..ec81bfe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.17.inc @@ -0,0 +1,8 @@ +define(); +echo $object -> define(); +Foo::define(); + +$c = new class extends Something{ + + public function someMethod() + { + // ... + } + +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.3.inc new file mode 100644 index 0000000..d4ae77e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.3.inc @@ -0,0 +1,6 @@ + +'; +} + +printHead(); +?> + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.5.inc new file mode 100644 index 0000000..7265c63 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.5.inc @@ -0,0 +1,2 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.6.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.6.inc new file mode 100644 index 0000000..e02fed4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Files/SideEffectsUnitTest.6.inc @@ -0,0 +1,9 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SideEffects sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR1\Sniffs\Files\SideEffectsSniff + */ +class SideEffectsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Set CLI values before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + if ($testFile === 'SideEffectsUnitTest.12.inc') { + $config->annotations = false; + } + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'SideEffectsUnitTest.3.inc': + case 'SideEffectsUnitTest.4.inc': + case 'SideEffectsUnitTest.5.inc': + case 'SideEffectsUnitTest.10.inc': + case 'SideEffectsUnitTest.12.inc': + case 'SideEffectsUnitTest.15.inc': + case 'SideEffectsUnitTest.16.inc': + return [1 => 1]; + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Methods/CamelCapsMethodNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Methods/CamelCapsMethodNameUnitTest.inc new file mode 100644 index 0000000..7381517 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests/Methods/CamelCapsMethodNameUnitTest.inc @@ -0,0 +1,81 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR1\Tests\Methods; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the CamelCapsMethodName sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR1\Sniffs\Methods\CamelCapsMethodNameSniff + */ +class CamelCapsMethodNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 6 => 1, + 7 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 17 => 1, + 21 => 1, + 25 => 1, + 26 => 1, + 77 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/ruleset.xml new file mode 100644 index 0000000..65cbe20 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR1/ruleset.xml @@ -0,0 +1,47 @@ + + + The PSR1 coding standard. + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClassInstantiationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClassInstantiationStandard.xml new file mode 100644 index 0000000..ae24611 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClassInstantiationStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClosingBraceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClosingBraceStandard.xml new file mode 100644 index 0000000..b59d734 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClosingBraceStandard.xml @@ -0,0 +1,35 @@ + + + + + + + + +function bar() +{ + // Function content. +} + ]]> + + + echo 'Hello!'; + +function bar() +{ + // Function content. +} //end bar() + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/OpeningBraceSpaceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/OpeningBraceSpaceStandard.xml new file mode 100644 index 0000000..818bbe8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/OpeningBraceSpaceStandard.xml @@ -0,0 +1,32 @@ + + + + + + + + public function bar() + { + // Method content. + } +} + ]]> + + + + public function bar() + { + // Method content. + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/ControlStructures/BooleanOperatorPlacementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/ControlStructures/BooleanOperatorPlacementStandard.xml new file mode 100644 index 0000000..805e15c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/ControlStructures/BooleanOperatorPlacementStandard.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Files/OpenTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Files/OpenTagStandard.xml new file mode 100644 index 0000000..20db18b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Files/OpenTagStandard.xml @@ -0,0 +1,40 @@ + + + + + + + + +echo 'hi'; + ]]> + + + echo 'hi'; + ]]> + + + + + + + + + + + ]]> + + + + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Functions/NullableTypeDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Functions/NullableTypeDeclarationStandard.xml new file mode 100644 index 0000000..2032c9a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Functions/NullableTypeDeclarationStandard.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Keywords/ShortFormTypeKeywordsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Keywords/ShortFormTypeKeywordsStandard.xml new file mode 100644 index 0000000..9bb5a8a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Keywords/ShortFormTypeKeywordsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + (boolean) $isValid; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Namespaces/CompoundNamespaceDepthStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Namespaces/CompoundNamespaceDepthStandard.xml new file mode 100644 index 0000000..b74e8b4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Namespaces/CompoundNamespaceDepthStandard.xml @@ -0,0 +1,28 @@ + + + + + + + + + + SubnamespaceOne\AnotherNamespace\ClassA, + SubnamespaceOne\ClassB, + ClassZ, +}; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Operators/OperatorSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Operators/OperatorSpacingStandard.xml new file mode 100644 index 0000000..981b1d9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Operators/OperatorSpacingStandard.xml @@ -0,0 +1,27 @@ + + + + + + + $b) { + $variable = $foo ? 'foo' : 'bar'; +} + ]]> + + + $b) { + $variable=$foo?'foo':'bar'; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/AnonClassDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/AnonClassDeclarationSniff.php new file mode 100644 index 0000000..d4792f5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/AnonClassDeclarationSniff.php @@ -0,0 +1,246 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\FunctionCallArgumentSpacingSniff; +use PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff; +use PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff; +use PHP_CodeSniffer\Util\Tokens; + +class AnonClassDeclarationSniff extends ClassDeclarationSniff +{ + + /** + * The PSR2 MultiLineFunctionDeclarations sniff. + * + * @var \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff + */ + private $multiLineSniff = null; + + /** + * The Generic FunctionCallArgumentSpacing sniff. + * + * @var \PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\FunctionCallArgumentSpacingSniff + */ + private $functionCallSniff = null; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_ANON_CLASS]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + $this->multiLineSniff = new MultiLineFunctionDeclarationSniff(); + $this->functionCallSniff = new FunctionCallArgumentSpacingSniff(); + + $this->processOpen($phpcsFile, $stackPtr); + $this->processClose($phpcsFile, $stackPtr); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === true) { + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + if ($this->multiLineSniff->isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) === true) { + $this->processMultiLineArgumentList($phpcsFile, $stackPtr); + } else { + $this->processSingleLineArgumentList($phpcsFile, $stackPtr); + } + + $this->functionCallSniff->checkSpacing($phpcsFile, $stackPtr, $openBracket); + } + + $opener = $tokens[$stackPtr]['scope_opener']; + if ($tokens[$opener]['line'] === $tokens[$stackPtr]['line']) { + return; + } + + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($opener - 1), $stackPtr, true); + + $implements = $phpcsFile->findPrevious(T_IMPLEMENTS, ($opener - 1), $stackPtr); + if ($implements !== false + && $tokens[$opener]['line'] !== $tokens[$implements]['line'] + && $tokens[$opener]['line'] === $tokens[$prev]['line'] + ) { + // Opening brace must be on a new line as implements list wraps. + $error = 'Opening brace must be on the line after the last implemented interface'; + $fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceSameLine'); + if ($fix === true) { + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + $indent = str_repeat(' ', ($tokens[$first]['column'] - 1)); + $phpcsFile->fixer->beginChangeset(); + + if ($tokens[($prev + 1)]['code'] === \T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($prev + 1), ''); + } + + $phpcsFile->fixer->addNewline($prev); + $phpcsFile->fixer->addContentBefore($opener, $indent); + $phpcsFile->fixer->endChangeset(); + } + } + + if ($tokens[$opener]['line'] > ($tokens[$prev]['line'] + 1)) { + // Opening brace is on a new line, so there must be no blank line before it. + $error = 'Opening brace must not be preceded by a blank line'; + $fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceLine'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($prev + 1); $x < $opener; $x++) { + if ($tokens[$x]['line'] === $tokens[$prev]['line']) { + // Maintain existing newline. + continue; + } + + if ($tokens[$x]['line'] === $tokens[$opener]['line']) { + // Maintain existing indent. + break; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + }//end process() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processSingleLineArgumentList(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + if ($openBracket === ($closeBracket - 1)) { + return; + } + + if ($tokens[($openBracket + 1)]['code'] === T_WHITESPACE) { + $error = 'Space after opening parenthesis of single-line argument list prohibited'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterOpenBracket'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($openBracket + 1), ''); + } + } + + $spaceBeforeClose = 0; + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBracket - 1), $openBracket, true); + if ($tokens[$prev]['code'] === T_END_HEREDOC || $tokens[$prev]['code'] === T_END_NOWDOC) { + // Need a newline after these tokens, so ignore this rule. + return; + } + + if ($tokens[$prev]['line'] !== $tokens[$closeBracket]['line']) { + $spaceBeforeClose = 'newline'; + } else if ($tokens[($closeBracket - 1)]['code'] === T_WHITESPACE) { + $spaceBeforeClose = $tokens[($closeBracket - 1)]['length']; + } + + if ($spaceBeforeClose !== 0) { + $error = 'Space before closing parenthesis of single-line argument list prohibited'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeCloseBracket'); + if ($fix === true) { + if ($spaceBeforeClose === 'newline') { + $phpcsFile->fixer->beginChangeset(); + + $closingContent = ')'; + + $next = $phpcsFile->findNext(T_WHITESPACE, ($closeBracket + 1), null, true); + if ($tokens[$next]['code'] === T_SEMICOLON) { + $closingContent .= ';'; + for ($i = ($closeBracket + 1); $i <= $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + + // We want to jump over any whitespace or inline comment and + // move the closing parenthesis after any other token. + $prev = ($closeBracket - 1); + while (isset(Tokens::$emptyTokens[$tokens[$prev]['code']]) === true) { + if (($tokens[$prev]['code'] === T_COMMENT) + && (strpos($tokens[$prev]['content'], '*/') !== false) + ) { + break; + } + + $prev--; + } + + $phpcsFile->fixer->addContent($prev, $closingContent); + + $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBracket - 1), null, true); + for ($i = ($prevNonWhitespace + 1); $i <= $closeBracket; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($closeBracket - 1), ''); + }//end if + }//end if + }//end if + + }//end processSingleLineArgumentList() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processMultiLineArgumentList(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + + $this->multiLineSniff->processBracket($phpcsFile, $openBracket, $tokens, 'argument'); + $this->multiLineSniff->processArgumentList($phpcsFile, $stackPtr, $this->indent, 'argument'); + + }//end processMultiLineArgumentList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php new file mode 100644 index 0000000..2130b8d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php @@ -0,0 +1,115 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassInstantiationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_NEW]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Find the class name. + $allowed = [ + T_STRING => T_STRING, + T_NS_SEPARATOR => T_NS_SEPARATOR, + T_SELF => T_SELF, + T_STATIC => T_STATIC, + T_PARENT => T_PARENT, + T_VARIABLE => T_VARIABLE, + T_DOLLAR => T_DOLLAR, + T_OBJECT_OPERATOR => T_OBJECT_OPERATOR, + T_NULLSAFE_OBJECT_OPERATOR => T_NULLSAFE_OBJECT_OPERATOR, + T_DOUBLE_COLON => T_DOUBLE_COLON, + ]; + + $allowed += Tokens::$emptyTokens; + + $classNameEnd = null; + for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { + if (isset($allowed[$tokens[$i]['code']]) === true) { + continue; + } + + // Skip over potential attributes for anonymous classes. + if ($tokens[$i]['code'] === T_ATTRIBUTE + && isset($tokens[$i]['attribute_closer']) === true + ) { + $i = $tokens[$i]['attribute_closer']; + continue; + } + + if ($tokens[$i]['code'] === T_OPEN_SQUARE_BRACKET + || $tokens[$i]['code'] === T_OPEN_CURLY_BRACKET + ) { + $i = $tokens[$i]['bracket_closer']; + continue; + } + + $classNameEnd = $i; + break; + }//end for + + if ($classNameEnd === null) { + return; + } + + if ($tokens[$classNameEnd]['code'] === T_ANON_CLASS) { + // Ignore anon classes. + return; + } + + if ($tokens[$classNameEnd]['code'] === T_OPEN_PARENTHESIS) { + // Using parenthesis. + return; + } + + if ($classNameEnd === $stackPtr) { + // Failed to find the class name. + return; + } + + $error = 'Parentheses must be used when instantiating a new class'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'MissingParentheses'); + if ($fix === true) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($classNameEnd - 1), null, true); + $phpcsFile->fixer->addContent($prev, '()'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClosingBraceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClosingBraceSniff.php new file mode 100644 index 0000000..82f215f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClosingBraceSniff.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClosingBraceSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $closer = $tokens[$stackPtr]['scope_closer']; + $next = $phpcsFile->findNext(T_WHITESPACE, ($closer + 1), null, true); + if ($next === false + || $tokens[$next]['line'] !== $tokens[$closer]['line'] + ) { + return; + } + + $error = 'Closing brace must not be followed by any comment or statement on the same line'; + $phpcsFile->addError($error, $closer, 'StatementAfter'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/OpeningBraceSpaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/OpeningBraceSpaceSniff.php new file mode 100644 index 0000000..261f702 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/OpeningBraceSpaceSniff.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OpeningBraceSpaceSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$ooScopeTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + $opener = $tokens[$stackPtr]['scope_opener']; + $next = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true); + if ($next === false + || $tokens[$next]['line'] <= ($tokens[$opener]['line'] + 1) + ) { + return; + } + + $error = 'Opening brace must not be followed by a blank line'; + $fix = $phpcsFile->addFixableError($error, $opener, 'Found'); + if ($fix === false) { + return; + } + + $phpcsFile->fixer->beginChangeset(); + for ($i = ($opener + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$opener]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/BooleanOperatorPlacementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/BooleanOperatorPlacementSniff.php new file mode 100644 index 0000000..dabb318 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/BooleanOperatorPlacementSniff.php @@ -0,0 +1,229 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class BooleanOperatorPlacementSniff implements Sniff +{ + + /** + * Used to restrict the placement of the boolean operator. + * + * Allowed value are "first" or "last". + * + * @var string|null + */ + public $allowOnly = null; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_WHILE, + T_SWITCH, + T_ELSEIF, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + ) { + return; + } + + $parenOpener = $tokens[$stackPtr]['parenthesis_opener']; + $parenCloser = $tokens[$stackPtr]['parenthesis_closer']; + + if ($tokens[$parenOpener]['line'] === $tokens[$parenCloser]['line']) { + // Conditions are all on the same line. + return; + } + + $find = [ + T_BOOLEAN_AND, + T_BOOLEAN_OR, + ]; + + if ($this->allowOnly === 'first' || $this->allowOnly === 'last') { + $position = $this->allowOnly; + } else { + $position = null; + } + + $operator = $parenOpener; + $error = false; + $operators = []; + + do { + $operator = $phpcsFile->findNext($find, ($operator + 1), $parenCloser); + if ($operator === false) { + break; + } + + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($operator - 1), $parenOpener, true); + if ($prev === false) { + // Parse error. + return; + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($operator + 1), $parenCloser, true); + if ($next === false) { + // Parse error. + return; + } + + $firstOnLine = false; + $lastOnLine = false; + + if ($tokens[$prev]['line'] < $tokens[$operator]['line']) { + // The boolean operator is the first content on the line. + $firstOnLine = true; + } + + if ($tokens[$next]['line'] > $tokens[$operator]['line']) { + // The boolean operator is the last content on the line. + $lastOnLine = true; + } + + if ($firstOnLine === true && $lastOnLine === true) { + // The operator is the only content on the line. + // Don't record it because we can't determine + // placement information from looking at it. + continue; + } + + $operators[] = $operator; + + if ($firstOnLine === false && $lastOnLine === false) { + // It's in the middle of content, so we can't determine + // placement information from looking at it, but we may + // still need to process it. + continue; + } + + if ($firstOnLine === true) { + if ($position === null) { + $position = 'first'; + } + + if ($position !== 'first') { + $error = true; + } + } else { + if ($position === null) { + $position = 'last'; + } + + if ($position !== 'last') { + $error = true; + } + } + } while ($operator !== false); + + if ($error === false) { + return; + } + + switch ($this->allowOnly) { + case 'first': + $error = 'Boolean operators between conditions must be at the beginning of the line'; + break; + case 'last': + $error = 'Boolean operators between conditions must be at the end of the line'; + break; + default: + $error = 'Boolean operators between conditions must be at the beginning or end of the line, but not both'; + } + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FoundMixed'); + if ($fix === false) { + return; + } + + $phpcsFile->fixer->beginChangeset(); + foreach ($operators as $operator) { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($operator - 1), $parenOpener, true); + $next = $phpcsFile->findNext(T_WHITESPACE, ($operator + 1), $parenCloser, true); + + if ($position === 'last') { + if ($tokens[$next]['line'] === $tokens[$operator]['line']) { + if ($tokens[$prev]['line'] === $tokens[$operator]['line']) { + // Move the content after the operator to the next line. + if ($tokens[($operator + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($operator + 1), ''); + } + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $operator, true); + $padding = str_repeat(' ', ($tokens[$first]['column'] - 1)); + $phpcsFile->fixer->addContent($operator, $phpcsFile->eolChar.$padding); + } else { + // Move the operator to the end of the previous line. + if ($tokens[($operator + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($operator + 1), ''); + } + + $phpcsFile->fixer->addContent($prev, ' '.$tokens[$operator]['content']); + $phpcsFile->fixer->replaceToken($operator, ''); + } + }//end if + } else { + if ($tokens[$prev]['line'] === $tokens[$operator]['line']) { + if ($tokens[$next]['line'] === $tokens[$operator]['line']) { + // Move the operator, and the rest of the expression, to the next line. + if ($tokens[($operator - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($operator - 1), ''); + } + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $operator, true); + $padding = str_repeat(' ', ($tokens[$first]['column'] - 1)); + $phpcsFile->fixer->addContentBefore($operator, $phpcsFile->eolChar.$padding); + } else { + // Move the operator to the start of the next line. + if ($tokens[($operator - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($operator - 1), ''); + } + + $phpcsFile->fixer->addContentBefore($next, $tokens[$operator]['content'].' '); + $phpcsFile->fixer->replaceToken($operator, ''); + } + }//end if + }//end if + }//end foreach + + $phpcsFile->fixer->endChangeset(); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/ControlStructureSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/ControlStructureSpacingSniff.php new file mode 100644 index 0000000..9a200aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/ControlStructureSpacingSniff.php @@ -0,0 +1,207 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ControlStructureSpacingSniff as PSR2ControlStructureSpacing; +use PHP_CodeSniffer\Util\Tokens; + +class ControlStructureSpacingSniff implements Sniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + /** + * Instance of the PSR2 ControlStructureSpacingSniff sniff. + * + * @var \PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ControlStructureSpacingSniff + */ + private $psr2ControlStructureSpacing; + + + /** + * Constructor. + */ + public function __construct() + { + $this->psr2ControlStructureSpacing = new PSR2ControlStructureSpacing(); + + }//end __construct() + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_WHILE, + T_FOREACH, + T_FOR, + T_SWITCH, + T_ELSEIF, + T_CATCH, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + ) { + return; + } + + $parenOpener = $tokens[$stackPtr]['parenthesis_opener']; + $parenCloser = $tokens[$stackPtr]['parenthesis_closer']; + + if ($tokens[$parenOpener]['line'] === $tokens[$parenCloser]['line']) { + // Conditions are all on the same line, so follow PSR2. + return $this->psr2ControlStructureSpacing->process($phpcsFile, $stackPtr); + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($parenOpener + 1), $parenCloser, true); + if ($next === false) { + // No conditions; parse error. + return; + } + + // Check the first expression. + if ($tokens[$next]['line'] !== ($tokens[$parenOpener]['line'] + 1)) { + $error = 'The first expression of a multi-line control structure must be on the line after the opening parenthesis'; + $fix = $phpcsFile->addFixableError($error, $next, 'FirstExpressionLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($parenOpener); + } + } + + // Check the indent of each line. + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + $requiredIndent = ($tokens[$first]['column'] + $this->indent - 1); + for ($i = $parenOpener; $i < $parenCloser; $i++) { + if ($tokens[$i]['column'] !== 1 + || $tokens[($i + 1)]['line'] > $tokens[$i]['line'] + || isset(Tokens::$commentTokens[$tokens[$i]['code']]) === true + ) { + continue; + } + + if (($i + 1) === $parenCloser) { + break; + } + + // Leave indentation inside multi-line strings. + if (isset(Tokens::$textStringTokens[$tokens[$i]['code']]) === true + || isset(Tokens::$heredocTokens[$tokens[$i]['code']]) === true + ) { + continue; + } + + if ($tokens[$i]['code'] !== T_WHITESPACE) { + $foundIndent = 0; + } else { + $foundIndent = $tokens[$i]['length']; + } + + if ($foundIndent < $requiredIndent) { + $error = 'Each line in a multi-line control structure must be indented at least once; expected at least %s spaces, but found %s'; + $data = [ + $requiredIndent, + $foundIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $i, 'LineIndent', $data); + if ($fix === true) { + $padding = str_repeat(' ', $requiredIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($i, $padding); + } else { + $phpcsFile->fixer->replaceToken($i, $padding); + } + } + } + }//end for + + // Check the closing parenthesis. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($parenCloser - 1), $parenOpener, true); + if ($tokens[$parenCloser]['line'] !== ($tokens[$prev]['line'] + 1)) { + $error = 'The closing parenthesis of a multi-line control structure must be on the line after the last expression'; + $fix = $phpcsFile->addFixableError($error, $parenCloser, 'CloseParenthesisLine'); + if ($fix === true) { + if ($tokens[$parenCloser]['line'] === $tokens[$prev]['line']) { + $phpcsFile->fixer->addNewlineBefore($parenCloser); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $parenCloser; $i++) { + // Maintain existing newline. + if ($tokens[$i]['line'] === $tokens[$prev]['line']) { + continue; + } + + // Maintain existing indent. + if ($tokens[$i]['line'] === $tokens[$parenCloser]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + if ($tokens[$parenCloser]['line'] !== $tokens[$prev]['line']) { + $requiredIndent = ($tokens[$first]['column'] - 1); + $foundIndent = ($tokens[$parenCloser]['column'] - 1); + if ($foundIndent !== $requiredIndent) { + $error = 'The closing parenthesis of a multi-line control structure must be indented to the same level as start of the control structure; expected %s spaces but found %s'; + $data = [ + $requiredIndent, + $foundIndent, + ]; + $fix = $phpcsFile->addFixableError($error, $parenCloser, 'CloseParenthesisIndent', $data); + if ($fix === true) { + $padding = str_repeat(' ', $requiredIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($parenCloser, $padding); + } else { + $phpcsFile->fixer->replaceToken(($parenCloser - 1), $padding); + } + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/DeclareStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/DeclareStatementSniff.php new file mode 100644 index 0000000..b59d6c5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/DeclareStatementSniff.php @@ -0,0 +1,256 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DeclareStatementSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DECLARE]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // Allow a byte-order mark. + $tokens = $phpcsFile->getTokens(); + + // There should be no space between declare keyword and opening parenthesis. + $parenthesis = ($stackPtr + 1); + if ($tokens[($stackPtr + 1)]['type'] !== 'T_OPEN_PARENTHESIS') { + $parenthesis = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $error = 'Expected no space between declare keyword and opening parenthesis in a declare statement'; + + if ($tokens[$parenthesis]['type'] === 'T_OPEN_PARENTHESIS') { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceFoundAfterDeclare'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + } else { + $phpcsFile->addError($error, $parenthesis, 'SpaceFoundAfterDeclare'); + $parenthesis = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($parenthesis + 1)); + } + } + + // There should be no space between open parenthesis and the directive. + $string = $phpcsFile->findNext(T_WHITESPACE, ($parenthesis + 1), null, true); + if ($parenthesis !== false) { + if ($tokens[($parenthesis + 1)]['type'] !== 'T_STRING') { + $error = 'Expected no space between opening parenthesis and directive in a declare statement'; + + if ($tokens[$string]['type'] === 'T_STRING') { + $fix = $phpcsFile->addFixableError($error, $parenthesis, 'SpaceFoundBeforeDirective'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($parenthesis + 1), ''); + } + } else { + $phpcsFile->addError($error, $string, 'SpaceFoundBeforeDirective'); + $string = $phpcsFile->findNext(T_STRING, ($string + 1)); + } + } + } + + // There should be no space between directive and the equal sign. + $equals = $phpcsFile->findNext(T_WHITESPACE, ($string + 1), null, true); + if ($string !== false) { + // The directive must be in lowercase. + if ($tokens[$string]['content'] !== strtolower($tokens[$string]['content'])) { + $error = 'The directive of a declare statement must be in lowercase'; + $fix = $phpcsFile->addFixableError($error, $string, 'DirectiveNotLowercase'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($string, strtolower($tokens[$string]['content'])); + } + } + + if ($tokens[($string + 1)]['type'] !== 'T_EQUAL') { + $error = 'Expected no space between directive and the equals sign in a declare statement'; + + if ($tokens[$equals]['type'] === 'T_EQUAL') { + $fix = $phpcsFile->addFixableError($error, $equals, 'SpaceFoundAfterDirective'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($string + 1), ''); + } + } else { + $phpcsFile->addError($error, $equals, 'SpaceFoundAfterDirective'); + $equals = $phpcsFile->findNext(T_EQUAL, ($equals + 1)); + } + } + }//end if + + // There should be no space between equal sign and directive value. + $value = $phpcsFile->findNext(T_WHITESPACE, ($equals + 1), null, true); + if ($equals !== false) { + if ($tokens[($equals + 1)]['type'] !== 'T_LNUMBER') { + $error = 'Expected no space between equal sign and the directive value in a declare statement'; + + if ($tokens[$value]['type'] === 'T_LNUMBER') { + $fix = $phpcsFile->addFixableError($error, $value, 'SpaceFoundBeforeDirectiveValue'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($equals + 1), ''); + } + } else { + $phpcsFile->addError($error, $value, 'SpaceFoundBeforeDirectiveValue'); + $value = $phpcsFile->findNext(T_LNUMBER, ($value + 1)); + } + } + } + + $parenthesis = $phpcsFile->findNext(T_WHITESPACE, ($value + 1), null, true); + if ($value !== false) { + if ($tokens[($value + 1)]['type'] !== 'T_CLOSE_PARENTHESIS') { + $error = 'Expected no space between the directive value and closing parenthesis in a declare statement'; + + if ($tokens[$parenthesis]['type'] === 'T_CLOSE_PARENTHESIS') { + $fix = $phpcsFile->addFixableError($error, $parenthesis, 'SpaceFoundAfterDirectiveValue'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($value + 1), ''); + } + } else { + $phpcsFile->addError($error, $parenthesis, 'SpaceFoundAfterDirectiveValue'); + $parenthesis = $phpcsFile->findNext(T_CLOSE_PARENTHESIS, ($parenthesis + 1)); + } + } + } + + // Check for semicolon. + $curlyBracket = false; + if ($tokens[($parenthesis + 1)]['type'] !== 'T_SEMICOLON') { + $token = $phpcsFile->findNext(T_WHITESPACE, ($parenthesis + 1), null, true); + + if ($tokens[$token]['type'] === 'T_OPEN_CURLY_BRACKET') { + // Block declaration. + $curlyBracket = $token; + } else if ($tokens[$token]['type'] === 'T_SEMICOLON') { + $error = 'Expected no space between the closing parenthesis and the semicolon in a declare statement'; + $fix = $phpcsFile->addFixableError($error, $parenthesis, 'SpaceFoundBeforeSemicolon'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($parenthesis + 1), ''); + } + } else if ($tokens[$token]['type'] === 'T_CLOSE_TAG') { + if ($tokens[($parenthesis)]['line'] !== $tokens[$token]['line']) { + // Close tag must be on the same line.. + $error = 'The close tag must be on the same line as the declare statement'; + $fix = $phpcsFile->addFixableError($error, $parenthesis, 'CloseTagOnNewLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($parenthesis + 1), ' '); + } + } + } else { + $error = 'Expected no space between the closing parenthesis and the semicolon in a declare statement'; + $phpcsFile->addError($error, $parenthesis, 'SpaceFoundBeforeSemicolon'); + + // See if there is a semicolon or curly bracket after this token. + $token = $phpcsFile->findNext([T_WHITESPACE, T_COMMENT], ($token + 1), null, true); + if ($tokens[$token]['type'] === 'T_OPEN_CURLY_BRACKET') { + $curlyBracket = $token; + } + }//end if + }//end if + + if ($curlyBracket !== false) { + $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($curlyBracket - 1), null, true); + $error = 'Expected one space between closing parenthesis and opening curly bracket in a declare statement'; + + // The opening curly bracket must on the same line with a single space between closing bracket. + if ($tokens[$prevToken]['type'] !== 'T_CLOSE_PARENTHESIS') { + $phpcsFile->addError($error, $curlyBracket, 'ExtraSpaceFoundAfterBracket'); + } else if ($phpcsFile->getTokensAsString(($prevToken + 1), ($curlyBracket - $prevToken - 1)) !== ' ') { + $fix = $phpcsFile->addFixableError($error, $curlyBracket, 'ExtraSpaceFoundAfterBracket'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($prevToken + 1), ' '); + $nextToken = ($prevToken + 2); + while ($nextToken !== $curlyBracket) { + $phpcsFile->fixer->replaceToken($nextToken, ''); + $nextToken++; + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + $closeCurlyBracket = $tokens[$curlyBracket]['bracket_closer']; + + $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($closeCurlyBracket - 1), null, true); + $nextToken = $phpcsFile->findNext([T_WHITESPACE, T_COMMENT], ($closeCurlyBracket + 1), null, true); + $line = $tokens[$closeCurlyBracket]['line']; + + // The closing curly bracket must be on a new line. + if ($tokens[$prevToken]['line'] === $line || $tokens[$nextToken]['line'] === $line) { + if ($tokens[$prevToken]['line'] === $line) { + $error = 'The closing curly bracket of a declare statement must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $prevToken, 'CurlyBracketNotOnNewLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($prevToken); + } + } + }//end if + + // Closing curly bracket must align with the declare keyword. + if ($tokens[$stackPtr]['column'] !== $tokens[$closeCurlyBracket]['column']) { + $error = 'The closing curly bracket of a declare statements must be aligned with the declare keyword'; + + $fix = $phpcsFile->addFixableError($error, $closeCurlyBracket, 'CloseBracketNotAligned'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($closeCurlyBracket - 1), str_repeat(' ', ($tokens[$stackPtr]['column'] - 1))); + } + } + + // The open curly bracket must be the last code on the line. + $token = $phpcsFile->findNext(Tokens::$emptyTokens, ($curlyBracket + 1), null, true); + if ($tokens[$curlyBracket]['line'] === $tokens[$token]['line']) { + $error = 'The open curly bracket of a declare statement must be the last code on the line'; + $fix = $phpcsFile->addFixableError($error, $token, 'CodeFoundAfterCurlyBracket'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($token - 1), null, true); + + for ($i = ($prevToken + 1); $i < $token; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addNewLineBefore($token); + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php new file mode 100644 index 0000000..f06357d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php @@ -0,0 +1,429 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FileHeaderSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current + * token in the stack. + * + * @return int|void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $possibleHeaders = []; + + $searchFor = Tokens::$ooScopeTokens; + $searchFor[T_OPEN_TAG] = T_OPEN_TAG; + + $openTag = $stackPtr; + do { + $headerLines = $this->getHeaderLines($phpcsFile, $openTag); + if (empty($headerLines) === true && $openTag === $stackPtr) { + // No content in the file. + return; + } + + $possibleHeaders[$openTag] = $headerLines; + if (count($headerLines) > 1) { + break; + } + + $next = $phpcsFile->findNext($searchFor, ($openTag + 1)); + if (isset(Tokens::$ooScopeTokens[$tokens[$next]['code']]) === true) { + // Once we find an OO token, the file content has + // definitely started. + break; + } + + $openTag = $next; + } while ($openTag !== false); + + if ($openTag === false) { + // We never found a proper file header. + // If the file has multiple PHP open tags, we know + // that it must be a mix of PHP and HTML (or similar) + // so the header rules do not apply. + if (count($possibleHeaders) > 1) { + return $phpcsFile->numTokens; + } + + // There is only one possible header. + // If it is the first content in the file, it technically + // serves as the file header, and the open tag needs to + // have a newline after it. Otherwise, ignore it. + if ($stackPtr > 0) { + return $phpcsFile->numTokens; + } + + $openTag = $stackPtr; + } else if (count($possibleHeaders) > 1) { + // There are other PHP blocks before the file header. + $error = 'The file header must be the first content in the file'; + $phpcsFile->addError($error, $openTag, 'HeaderPosition'); + } else { + // The first possible header was the file header block, + // so make sure it is the first content in the file. + if ($openTag !== 0) { + // Allow for hashbang lines. + $hashbang = false; + if ($tokens[($openTag - 1)]['code'] === T_INLINE_HTML) { + $content = trim($tokens[($openTag - 1)]['content']); + if (substr($content, 0, 2) === '#!') { + $hashbang = true; + } + } + + if ($hashbang === false) { + $error = 'The file header must be the first content in the file'; + $phpcsFile->addError($error, $openTag, 'HeaderPosition'); + } + } + }//end if + + $this->processHeaderLines($phpcsFile, $possibleHeaders[$openTag]); + + return $phpcsFile->numTokens; + + }//end process() + + + /** + * Gather information about the statements inside a possible file header. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current + * token in the stack. + * + * @return array + */ + public function getHeaderLines(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($next === false) { + return []; + } + + $headerLines = []; + $headerLines[] = [ + 'type' => 'tag', + 'start' => $stackPtr, + 'end' => $stackPtr, + ]; + + $foundDocblock = false; + + $commentOpeners = Tokens::$scopeOpeners; + unset($commentOpeners[T_NAMESPACE]); + unset($commentOpeners[T_DECLARE]); + unset($commentOpeners[T_USE]); + unset($commentOpeners[T_IF]); + unset($commentOpeners[T_WHILE]); + unset($commentOpeners[T_FOR]); + unset($commentOpeners[T_FOREACH]); + unset($commentOpeners[T_DO]); + unset($commentOpeners[T_TRY]); + + do { + switch ($tokens[$next]['code']) { + case T_DOC_COMMENT_OPEN_TAG: + if ($foundDocblock === true) { + // Found a second docblock, so start of code. + break(2); + } + + // Make sure this is not a code-level docblock. + $end = $tokens[$next]['comment_closer']; + for ($docToken = ($end + 1); $docToken < $phpcsFile->numTokens; $docToken++) { + if (isset(Tokens::$emptyTokens[$tokens[$docToken]['code']]) === true) { + continue; + } + + if ($tokens[$docToken]['code'] === T_ATTRIBUTE + && isset($tokens[$docToken]['attribute_closer']) === true + ) { + $docToken = $tokens[$docToken]['attribute_closer']; + continue; + } + + break; + } + + if ($docToken === $phpcsFile->numTokens) { + $docToken--; + } + + if (isset($commentOpeners[$tokens[$docToken]['code']]) === false + && isset(Tokens::$methodPrefixes[$tokens[$docToken]['code']]) === false + && $tokens[$docToken]['code'] !== T_READONLY + ) { + // Check for an @var annotation. + $annotation = false; + for ($i = $next; $i < $end; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_TAG + && strtolower($tokens[$i]['content']) === '@var' + ) { + $annotation = true; + break; + } + } + + if ($annotation === false) { + $foundDocblock = true; + $headerLines[] = [ + 'type' => 'docblock', + 'start' => $next, + 'end' => $end, + ]; + } + }//end if + + $next = $end; + break; + case T_DECLARE: + case T_NAMESPACE: + if (isset($tokens[$next]['scope_opener']) === true) { + // If this statement is using bracketed syntax, it doesn't + // apply to the entire files and so is not part of header. + // The header has now ended and the main code block begins. + break(2); + } + + $end = $phpcsFile->findEndOfStatement($next); + + $headerLines[] = [ + 'type' => substr(strtolower($tokens[$next]['type']), 2), + 'start' => $next, + 'end' => $end, + ]; + + $next = $end; + break; + case T_USE: + $type = 'use'; + $useType = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + if ($useType !== false && $tokens[$useType]['code'] === T_STRING) { + $content = strtolower($tokens[$useType]['content']); + if ($content === 'function' || $content === 'const') { + $type .= ' '.$content; + } + } + + $end = $phpcsFile->findEndOfStatement($next); + + $headerLines[] = [ + 'type' => $type, + 'start' => $next, + 'end' => $end, + ]; + + $next = $end; + break; + default: + // Skip comments as PSR-12 doesn't say if these are allowed or not. + if (isset(Tokens::$commentTokens[$tokens[$next]['code']]) === true) { + $next = $phpcsFile->findNext(Tokens::$commentTokens, ($next + 1), null, true); + if ($next === false) { + // We reached the end of the file. + break(2); + } + + $next--; + break; + } + + // We found the start of the main code block. + break(2); + }//end switch + + $next = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true); + } while ($next !== false); + + return $headerLines; + + }//end getHeaderLines() + + + /** + * Check the spacing and grouping of the statements inside each header block. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $headerLines Header information, as sourced + * from getHeaderLines(). + * + * @return void + */ + public function processHeaderLines(File $phpcsFile, $headerLines) + { + $tokens = $phpcsFile->getTokens(); + + $found = []; + + foreach ($headerLines as $i => $line) { + if (isset($headerLines[($i + 1)]) === false + || $headerLines[($i + 1)]['type'] !== $line['type'] + ) { + // We're at the end of the current header block. + // Make sure there is a single blank line after + // this block. + $next = $phpcsFile->findNext(T_WHITESPACE, ($line['end'] + 1), null, true); + if ($next !== false && $tokens[$next]['line'] !== ($tokens[$line['end']]['line'] + 2)) { + $error = 'Header blocks must be separated by a single blank line'; + $fix = $phpcsFile->addFixableError($error, $line['end'], 'SpacingAfterBlock'); + if ($fix === true) { + if ($tokens[$next]['line'] === $tokens[$line['end']]['line']) { + $phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar.$phpcsFile->eolChar); + } else if ($tokens[$next]['line'] === ($tokens[$line['end']]['line'] + 1)) { + $phpcsFile->fixer->addNewline($line['end']); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($line['end'] + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === ($tokens[$line['end']]['line'] + 2)) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + // Make sure we haven't seen this next block before. + if (isset($headerLines[($i + 1)]) === true + && isset($found[$headerLines[($i + 1)]['type']]) === true + ) { + $error = 'Similar statements must be grouped together inside header blocks; '; + $error .= 'the first "%s" statement was found on line %s'; + $data = [ + $headerLines[($i + 1)]['type'], + $tokens[$found[$headerLines[($i + 1)]['type']]['start']]['line'], + ]; + $phpcsFile->addError($error, $headerLines[($i + 1)]['start'], 'IncorrectGrouping', $data); + } + } else if ($headerLines[($i + 1)]['type'] === $line['type']) { + // Still in the same block, so make sure there is no + // blank line after this statement. + $next = $phpcsFile->findNext(T_WHITESPACE, ($line['end'] + 1), null, true); + if ($tokens[$next]['line'] > ($tokens[$line['end']]['line'] + 1)) { + $error = 'Header blocks must not contain blank lines'; + $fix = $phpcsFile->addFixableError($error, $line['end'], 'SpacingInsideBlock'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($line['end'] + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$line['end']]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + if (isset($found[$line['type']]) === false) { + $found[$line['type']] = $line; + } + }//end foreach + + /* + Next, check that the order of the header blocks + is correct: + Opening php tag. + File-level docblock. + One or more declare statements. + The namespace declaration of the file. + One or more class-based use import statements. + One or more function-based use import statements. + One or more constant-based use import statements. + */ + + $blockOrder = [ + 'tag' => 'opening PHP tag', + 'docblock' => 'file-level docblock', + 'declare' => 'declare statements', + 'namespace' => 'namespace declaration', + 'use' => 'class-based use imports', + 'use function' => 'function-based use imports', + 'use const' => 'constant-based use imports', + ]; + + foreach (array_keys($found) as $type) { + if ($type === 'tag') { + // The opening tag is always in the correct spot. + continue; + } + + do { + $orderedType = next($blockOrder); + } while ($orderedType !== false && key($blockOrder) !== $type); + + if ($orderedType === false) { + // We didn't find the block type in the rest of the + // ordered array, so it is out of place. + // Error and reset the array to the correct position + // so we can check the next block. + reset($blockOrder); + $prevValidType = 'tag'; + do { + $orderedType = next($blockOrder); + if (isset($found[key($blockOrder)]) === true + && key($blockOrder) !== $type + ) { + $prevValidType = key($blockOrder); + } + } while ($orderedType !== false && key($blockOrder) !== $type); + + $error = 'The %s must follow the %s in the file header'; + $data = [ + $blockOrder[$type], + $blockOrder[$prevValidType], + ]; + $phpcsFile->addError($error, $found[$type]['start'], 'IncorrectOrder', $data); + }//end if + }//end foreach + + }//end processHeaderLines() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/ImportStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/ImportStatementSniff.php new file mode 100644 index 0000000..65198e8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/ImportStatementSniff.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ImportStatementSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_USE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Make sure this is not a closure USE group. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { + return; + } + + if ($phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens) === true) { + // This rule only applies to import statements. + return; + } + + if ($tokens[$next]['code'] === T_STRING + && (strtolower($tokens[$next]['content']) === 'function' + || strtolower($tokens[$next]['content']) === 'const') + ) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + } + + if ($tokens[$next]['code'] !== T_NS_SEPARATOR) { + return; + } + + $error = 'Import statements must not begin with a leading backslash'; + $fix = $phpcsFile->addFixableError($error, $next, 'LeadingSlash'); + + if ($fix === true) { + $phpcsFile->fixer->replaceToken($next, ''); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php new file mode 100644 index 0000000..d0ac5d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php @@ -0,0 +1,76 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class OpenTagSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current + * token in the stack. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($stackPtr !== 0) { + // This rule only applies if the open tag is on the first line of the file. + return $phpcsFile->numTokens; + } + + $tokens = $phpcsFile->getTokens(); + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($next === false) { + // Empty file. + return $phpcsFile->numTokens; + } + + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + // Tag is on a line by itself. + return $phpcsFile->numTokens; + } + + $next = $phpcsFile->findNext(T_INLINE_HTML, 0); + if ($next !== false) { + // This rule only applies to PHP-only files. + return $phpcsFile->numTokens; + } + + $error = 'Opening PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAlone'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($stackPtr); + } + + return $phpcsFile->numTokens; + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/NullableTypeDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/NullableTypeDeclarationSniff.php new file mode 100644 index 0000000..4314194 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/NullableTypeDeclarationSniff.php @@ -0,0 +1,94 @@ + + * @copyright 2006-2018 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class NullableTypeDeclarationSniff implements Sniff +{ + + /** + * An array of valid tokens after `T_NULLABLE` occurrences. + * + * @var array + */ + private $validTokens = [ + T_STRING => true, + T_NS_SEPARATOR => true, + T_CALLABLE => true, + T_SELF => true, + T_PARENT => true, + T_STATIC => true, + T_NULL => true, + T_FALSE => true, + T_TRUE => true, + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_NULLABLE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $nextNonEmptyPtr = $phpcsFile->findNext([T_WHITESPACE], ($stackPtr + 1), null, true); + if ($nextNonEmptyPtr === false) { + // Parse error or live coding. + return; + } + + $tokens = $phpcsFile->getTokens(); + $nextNonEmptyCode = $tokens[$nextNonEmptyPtr]['code']; + $validTokenFound = isset($this->validTokens[$nextNonEmptyCode]); + + if ($validTokenFound === true && $nextNonEmptyPtr === ($stackPtr + 1)) { + // Valid structure. + return; + } + + $error = 'There must not be a space between the question mark and the type in nullable type declarations'; + + if ($validTokenFound === true) { + // No other tokens then whitespace tokens found; fixable. + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'WhitespaceFound'); + if ($fix === true) { + for ($i = ($stackPtr + 1); $i < $nextNonEmptyPtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + + return; + } + + // Non-whitespace tokens found; trigger error but don't fix. + $phpcsFile->addError($error, $stackPtr, 'UnexpectedCharactersFound'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php new file mode 100644 index 0000000..cf1afc5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php @@ -0,0 +1,110 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ReturnTypeDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + T_FN, + ]; + + }//end register() + + + /** + * Processes this test when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + || $tokens[$stackPtr]['parenthesis_opener'] === null + || $tokens[$stackPtr]['parenthesis_closer'] === null + ) { + return; + } + + $methodProperties = $phpcsFile->getMethodProperties($stackPtr); + if ($methodProperties['return_type'] === '') { + return; + } + + $returnType = $methodProperties['return_type_token']; + if ($methodProperties['nullable_return_type'] === true) { + $returnType = $phpcsFile->findPrevious(T_NULLABLE, ($returnType - 1)); + } + + if ($tokens[($returnType - 1)]['code'] !== T_WHITESPACE + || $tokens[($returnType - 1)]['content'] !== ' ' + || $tokens[($returnType - 2)]['code'] !== T_COLON + ) { + $error = 'There must be a single space between the colon and type in a return type declaration'; + if ($tokens[($returnType - 1)]['code'] === T_WHITESPACE + && $tokens[($returnType - 2)]['code'] === T_COLON + ) { + $fix = $phpcsFile->addFixableError($error, $returnType, 'SpaceBeforeReturnType'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($returnType - 1), ' '); + } + } else if ($tokens[($returnType - 1)]['code'] === T_COLON) { + $fix = $phpcsFile->addFixableError($error, $returnType, 'SpaceBeforeReturnType'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($returnType, ' '); + } + } else { + $phpcsFile->addError($error, $returnType, 'SpaceBeforeReturnType'); + } + } + + $colon = $phpcsFile->findPrevious(T_COLON, $returnType); + if ($tokens[($colon - 1)]['code'] !== T_CLOSE_PARENTHESIS) { + $error = 'There must not be a space before the colon in a return type declaration'; + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($colon - 1), null, true); + if ($tokens[$prev]['code'] === T_CLOSE_PARENTHESIS) { + $fix = $phpcsFile->addFixableError($error, $colon, 'SpaceBeforeColon'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($prev + 1); $x < $colon; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError($error, $colon, 'SpaceBeforeColon'); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Keywords/ShortFormTypeKeywordsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Keywords/ShortFormTypeKeywordsSniff.php new file mode 100644 index 0000000..65d39eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Keywords/ShortFormTypeKeywordsSniff.php @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Keywords; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ShortFormTypeKeywordsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_BOOL_CAST, + T_INT_CAST, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $typecast = str_replace(' ', '', $tokens[$stackPtr]['content']); + $typecast = str_replace("\t", '', $typecast); + $typecast = trim($typecast, '()'); + $typecastLc = strtolower($typecast); + + if (($tokens[$stackPtr]['code'] === T_BOOL_CAST + && $typecastLc === 'bool') + || ($tokens[$stackPtr]['code'] === T_INT_CAST + && $typecastLc === 'int') + ) { + return; + } + + $error = 'Short form type keywords must be used. Found: %s'; + $data = [$tokens[$stackPtr]['content']]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'LongFound', $data); + if ($fix === true) { + if ($tokens[$stackPtr]['code'] === T_BOOL_CAST) { + $replacement = str_replace($typecast, 'bool', $tokens[$stackPtr]['content']); + } else { + $replacement = str_replace($typecast, 'int', $tokens[$stackPtr]['content']); + } + + $phpcsFile->fixer->replaceToken($stackPtr, $replacement); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Namespaces/CompoundNamespaceDepthSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Namespaces/CompoundNamespaceDepthSniff.php new file mode 100644 index 0000000..34e7f46 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Namespaces/CompoundNamespaceDepthSniff.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Namespaces; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class CompoundNamespaceDepthSniff implements Sniff +{ + + /** + * The max depth for compound namespaces. + * + * @var integer + */ + public $maxDepth = 2; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_USE_GROUP]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $this->maxDepth = (int) $this->maxDepth; + + $tokens = $phpcsFile->getTokens(); + + $end = $phpcsFile->findNext(T_CLOSE_USE_GROUP, ($stackPtr + 1)); + if ($end === false) { + return; + } + + $depth = 1; + for ($i = ($stackPtr + 1); $i <= $end; $i++) { + if ($tokens[$i]['code'] === T_NS_SEPARATOR) { + $depth++; + continue; + } + + if ($i === $end || $tokens[$i]['code'] === T_COMMA) { + // End of a namespace. + if ($depth > $this->maxDepth) { + $error = 'Compound namespaces cannot have a depth more than %s'; + $data = [$this->maxDepth]; + $phpcsFile->addError($error, $i, 'TooDeep', $data); + } + + $depth = 1; + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php new file mode 100644 index 0000000..0e58f18 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php @@ -0,0 +1,112 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff as SquizOperatorSpacingSniff; +use PHP_CodeSniffer\Util\Tokens; + +class OperatorSpacingSniff extends SquizOperatorSpacingSniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + parent::register(); + + $targets = Tokens::$comparisonTokens; + $targets += Tokens::$operators; + $targets += Tokens::$assignmentTokens; + $targets += Tokens::$booleanOperators; + $targets[] = T_INLINE_THEN; + $targets[] = T_INLINE_ELSE; + $targets[] = T_STRING_CONCAT; + $targets[] = T_INSTANCEOF; + + return $targets; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($this->isOperator($phpcsFile, $stackPtr) === false) { + return; + } + + $operator = $tokens[$stackPtr]['content']; + + $checkBefore = true; + $checkAfter = true; + + // Skip short ternary. + if ($tokens[($stackPtr)]['code'] === T_INLINE_ELSE + && $tokens[($stackPtr - 1)]['code'] === T_INLINE_THEN + ) { + $checkBefore = false; + } + + // Skip operator with comment on previous line. + if ($tokens[($stackPtr - 1)]['code'] === T_COMMENT + && $tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line'] + ) { + $checkBefore = false; + } + + if (isset($tokens[($stackPtr + 1)]) === true) { + // Skip short ternary. + if ($tokens[$stackPtr]['code'] === T_INLINE_THEN + && $tokens[($stackPtr + 1)]['code'] === T_INLINE_ELSE + ) { + $checkAfter = false; + } + } else { + // Skip partial files. + $checkAfter = false; + } + + if ($checkBefore === true && $tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected at least 1 space before "%s"; 0 found'; + $data = [$operator]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBefore', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + } + + if ($checkAfter === true && $tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected at least 1 space after "%s"; 0 found'; + $data = [$operator]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfter', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Properties/ConstantVisibilitySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Properties/ConstantVisibilitySniff.php new file mode 100644 index 0000000..8bcf0d5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Properties/ConstantVisibilitySniff.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Properties; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ConstantVisibilitySniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CONST]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Make sure this is a class constant. + if ($phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens) === false) { + return; + } + + $ignore = Tokens::$emptyTokens; + $ignore[] = T_FINAL; + + $prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true); + if (isset(Tokens::$scopeModifiers[$tokens[$prev]['code']]) === true) { + return; + } + + $error = 'Visibility must be declared on all constants if your project supports PHP 7.1 or later'; + $phpcsFile->addWarning($error, $stackPtr, 'NotFound'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Traits/UseDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Traits/UseDeclarationSniff.php new file mode 100644 index 0000000..70e99d7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Traits/UseDeclarationSniff.php @@ -0,0 +1,700 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Sniffs\Traits; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UseDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_USE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void|int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Needs to be a use statement directly inside a class. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + if (isset(Tokens::$ooScopeTokens[current($conditions)]) === false) { + return; + } + + $ooToken = key($conditions); + $opener = $tokens[$ooToken]['scope_opener']; + + // Figure out where all the use statements are. + $useTokens = [$stackPtr]; + for ($i = ($stackPtr + 1); $i < $tokens[$ooToken]['scope_closer']; $i++) { + if ($tokens[$i]['code'] === T_USE) { + $useTokens[] = $i; + } + + if (isset($tokens[$i]['scope_closer']) === true) { + $i = $tokens[$i]['scope_closer']; + } + } + + $numUseTokens = count($useTokens); + foreach ($useTokens as $usePos => $useToken) { + if ($usePos === 0) { + /* + This is the first use statement. + */ + + // The first non-comment line must be the use line. + $lastValidContent = $useToken; + for ($i = ($useToken - 1); $i > $opener; $i--) { + if ($tokens[$i]['code'] === T_WHITESPACE + && ($tokens[($i - 1)]['line'] === $tokens[$i]['line'] + || $tokens[($i + 1)]['line'] === $tokens[$i]['line']) + ) { + continue; + } + + if (isset(Tokens::$commentTokens[$tokens[$i]['code']]) === true) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + // Skip past the comment. + $i = $tokens[$i]['comment_opener']; + } + + $lastValidContent = $i; + + continue; + } + + break; + }//end for + + if ($tokens[$lastValidContent]['line'] !== ($tokens[$opener]['line'] + 1)) { + $error = 'The first trait import statement must be declared on the first non-comment line after the %s opening brace'; + $data = [strtolower($tokens[$ooToken]['content'])]; + + // Figure out if we can fix this error. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($useToken - 1), ($opener - 1), true); + if ($tokens[$prev]['line'] === $tokens[$opener]['line']) { + $fix = $phpcsFile->addFixableError($error, $useToken, 'UseAfterBrace', $data); + if ($fix === true) { + // We know that the USE statements is the first non-comment content + // in the class, so we just need to remove blank lines. + $phpcsFile->fixer->beginChangeset(); + for ($i = ($useToken - 1); $i > $opener; $i--) { + if ($tokens[$i]['line'] === $tokens[$opener]['line']) { + break; + } + + if ($tokens[$i]['line'] === $tokens[$useToken]['line']) { + continue; + } + + if ($tokens[$i]['code'] === T_WHITESPACE + && $tokens[($i - 1)]['line'] !== $tokens[$i]['line'] + && $tokens[($i + 1)]['line'] !== $tokens[$i]['line'] + ) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + if (isset(Tokens::$commentTokens[$tokens[$i]['code']]) === true) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + // Skip past the comment. + $i = $tokens[$i]['comment_opener']; + } + + $lastValidContent = $i; + } + }//end for + + $phpcsFile->fixer->endChangeset(); + }//end if + } else { + $phpcsFile->addError($error, $useToken, 'UseAfterBrace', $data); + }//end if + }//end if + } else { + // Make sure this use statement is not on the same line as the previous one. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($useToken - 1), null, true); + if ($prev !== false && $tokens[$prev]['line'] === $tokens[$useToken]['line']) { + $error = 'Each imported trait must be on its own line'; + $prevNonWs = $phpcsFile->findPrevious(T_WHITESPACE, ($useToken - 1), null, true); + if ($prevNonWs !== $prev) { + $phpcsFile->addError($error, $useToken, 'SpacingBeforeImport'); + } else { + $fix = $phpcsFile->addFixableError($error, $useToken, 'SpacingBeforeImport'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($useToken - 1); $x > $prev; $x--) { + if ($tokens[$x]['line'] === $tokens[$useToken]['line'] + ) { + // Preserve indent. + continue; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addNewline($prev); + if ($tokens[$prev]['line'] === $tokens[$useToken]['line']) { + if ($tokens[($useToken - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($useToken - 1), ''); + } + + $padding = str_repeat(' ', ($tokens[$useTokens[0]]['column'] - 1)); + $phpcsFile->fixer->addContent($prev, $padding); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + }//end if + }//end if + + $error = 'Expected 1 space after USE in trait import statement; %s found'; + if ($tokens[($useToken + 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $useToken, 'SpaceAfterUse', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($useToken, ' '); + } + } else if ($tokens[($useToken + 1)]['content'] !== ' ') { + $next = $phpcsFile->findNext(T_WHITESPACE, ($useToken + 1), null, true); + if ($tokens[$next]['line'] !== $tokens[$useToken]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($useToken + 1)]['length']; + } + + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $useToken, 'SpaceAfterUse', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($useToken + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContent($useToken, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($useToken + 1), ' '); + } + } + }//end if + + // Check the formatting of the statement. + if (isset($tokens[$useToken]['scope_opener']) === true) { + $this->processUseGroup($phpcsFile, $useToken); + $end = $tokens[$useToken]['scope_closer']; + } else { + $this->processUseStatement($phpcsFile, $useToken); + $end = $phpcsFile->findNext(T_SEMICOLON, ($useToken + 1)); + if ($end === false) { + // Syntax error. + return; + } + } + + if ($usePos === ($numUseTokens - 1)) { + /* + This is the last use statement. + */ + + $next = $phpcsFile->findNext(T_WHITESPACE, ($end + 1), null, true); + if ($next === $tokens[$ooToken]['scope_closer']) { + // Last content in the class. + $closer = $tokens[$ooToken]['scope_closer']; + if ($tokens[$closer]['line'] > ($tokens[$end]['line'] + 1)) { + $error = 'There must be no blank line after the last trait import statement at the bottom of a %s'; + $data = [strtolower($tokens[$ooToken]['content'])]; + $fix = $phpcsFile->addFixableError($error, $end, 'BlankLineAfterLastUse', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($end + 1); $i < $closer; $i++) { + if ($tokens[$i]['line'] === $tokens[$end]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$closer]['line']) { + // Don't remove indents. + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + } else if ($tokens[$next]['code'] !== T_USE) { + // Comments are allowed on the same line as the use statement, so make sure + // we don't error for those. + for ($next = ($end + 1); $next < $tokens[$ooToken]['scope_closer']; $next++) { + if ($tokens[$next]['code'] === T_WHITESPACE) { + continue; + } + + if (isset(Tokens::$commentTokens[$tokens[$next]['code']]) === true + && $tokens[$next]['line'] === $tokens[$end]['line'] + ) { + continue; + } + + break; + } + + if ($tokens[$next]['line'] <= ($tokens[$end]['line'] + 1)) { + $error = 'There must be a blank line following the last trait import statement'; + $fix = $phpcsFile->addFixableError($error, $end, 'NoBlankLineAfterUse'); + if ($fix === true) { + if ($tokens[$next]['line'] === $tokens[$useToken]['line']) { + $phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar.$phpcsFile->eolChar); + } else { + for ($i = ($next - 1); $i > $end; $i--) { + if ($tokens[$i]['line'] !== $tokens[$next]['line']) { + break; + } + } + + $phpcsFile->fixer->addNewlineBefore(($i + 1)); + } + } + } + }//end if + } else { + // Ensure use statements are grouped. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + if ($next !== $useTokens[($usePos + 1)]) { + $error = 'Imported traits must be grouped together'; + $phpcsFile->addError($error, $useTokens[($usePos + 1)], 'NotGrouped'); + } + }//end if + }//end foreach + + return $tokens[$ooToken]['scope_closer']; + + }//end process() + + + /** + * Processes a group use statement. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processUseGroup(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $opener = $tokens[$stackPtr]['scope_opener']; + $closer = $tokens[$stackPtr]['scope_closer']; + + if ($tokens[$opener]['line'] !== $tokens[$stackPtr]['line']) { + $error = 'The opening brace of a trait import statement must be on the same line as the USE keyword'; + // Figure out if we can fix this error. + $canFix = true; + for ($i = ($stackPtr + 1); $i < $opener; $i++) { + if ($tokens[$i]['line'] !== $tokens[($i + 1)]['line'] + && $tokens[$i]['code'] !== T_WHITESPACE + ) { + $canFix = false; + break; + } + } + + if ($canFix === true) { + $fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceNewLine'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($stackPtr + 1); $i < $opener; $i++) { + if ($tokens[$i]['line'] !== $tokens[($i + 1)]['line']) { + // Everything should have a single space around it. + $phpcsFile->fixer->replaceToken($i, ' '); + } + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->addError($error, $opener, 'OpenBraceNewLine'); + } + }//end if + + $error = 'Expected 1 space before opening brace in trait import statement; %s found'; + if ($tokens[($opener - 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $opener, 'SpaceBeforeOpeningBrace', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($opener, ' '); + } + } else if ($tokens[($opener - 1)]['content'] !== ' ') { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($opener - 1), null, true); + if ($tokens[$prev]['line'] !== $tokens[$opener]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($opener - 1)]['length']; + } + + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $opener, 'SpaceBeforeOpeningBrace', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($opener - 1); $x > $prev; $x--) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContentBefore($opener, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($opener - 1), ' '); + } + } + }//end if + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($opener + 1), ($closer - 1), true); + if ($next !== false && $tokens[$next]['line'] !== ($tokens[$opener]['line'] + 1)) { + $error = 'First trait conflict resolution statement must be on the line after the opening brace'; + $nextNonWs = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), ($closer - 1), true); + if ($nextNonWs !== $next) { + $phpcsFile->addError($error, $opener, 'SpaceAfterOpeningBrace'); + } else { + $fix = $phpcsFile->addFixableError($error, $opener, 'SpaceAfterOpeningBrace'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($opener + 1); $x < $next; $x++) { + if ($tokens[$x]['line'] === $tokens[$next]['line']) { + // Preserve indent. + break; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addNewline($opener); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + for ($i = ($stackPtr + 1); $i < $opener; $i++) { + if ($tokens[$i]['code'] !== T_COMMA) { + continue; + } + + if ($tokens[($i - 1)]['code'] === T_WHITESPACE) { + $error = 'Expected no space before comma in trait import statement; %s found'; + $data = [$tokens[($i - 1)]['length']]; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($i - 1), ''); + } + } + + $error = 'Expected 1 space after comma in trait import statement; %s found'; + if ($tokens[($i + 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterComma', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($i, ' '); + } + } else if ($tokens[($i + 1)]['content'] !== ' ') { + $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $opener, true); + if ($tokens[$next]['line'] !== $tokens[$i]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($i + 1)]['length']; + } + + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterComma', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($i + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContent($i, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($i + 1), ' '); + } + } + }//end if + }//end for + + for ($i = ($opener + 1); $i < $closer; $i++) { + if ($tokens[$i]['code'] === T_INSTEADOF) { + $error = 'Expected 1 space before INSTEADOF in trait import statement; %s found'; + if ($tokens[($i - 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeInsteadof', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($i, ' '); + } + } else if ($tokens[($i - 1)]['content'] !== ' ') { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), $opener, true); + if ($tokens[$prev]['line'] !== $tokens[$i]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($i - 1)]['length']; + } + + $data = [$found]; + + $prevNonWs = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), $opener, true); + if ($prevNonWs !== $prev) { + $phpcsFile->addError($error, $i, 'SpaceBeforeInsteadof', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeInsteadof', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($i - 1); $x > $prev; $x--) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContentBefore($i, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($i - 1), ' '); + } + } + } + }//end if + + $error = 'Expected 1 space after INSTEADOF in trait import statement; %s found'; + if ($tokens[($i + 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterInsteadof', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($i, ' '); + } + } else if ($tokens[($i + 1)]['content'] !== ' ') { + $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $closer, true); + if ($tokens[$next]['line'] !== $tokens[$i]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($i + 1)]['length']; + } + + $data = [$found]; + + $nextNonWs = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), $closer, true); + if ($nextNonWs !== $next) { + $phpcsFile->addError($error, $i, 'SpaceAfterInsteadof', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterInsteadof', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($i + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContent($i, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($i + 1), ' '); + } + } + } + }//end if + }//end if + + if ($tokens[$i]['code'] === T_AS) { + $error = 'Expected 1 space before AS in trait import statement; %s found'; + if ($tokens[($i - 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeAs', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($i, ' '); + } + } else if ($tokens[($i - 1)]['content'] !== ' ') { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), $opener, true); + if ($tokens[$prev]['line'] !== $tokens[$i]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($i - 1)]['length']; + } + + $data = [$found]; + + $prevNonWs = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), $opener, true); + if ($prevNonWs !== $prev) { + $phpcsFile->addError($error, $i, 'SpaceBeforeAs', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeAs', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($i - 1); $x > $prev; $x--) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContentBefore($i, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($i - 1), ' '); + } + } + } + }//end if + + $error = 'Expected 1 space after AS in trait import statement; %s found'; + if ($tokens[($i + 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterAs', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($i, ' '); + } + } else if ($tokens[($i + 1)]['content'] !== ' ') { + $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $closer, true); + if ($tokens[$next]['line'] !== $tokens[$i]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($i + 1)]['length']; + } + + $data = [$found]; + + $nextNonWs = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), $closer, true); + if ($nextNonWs !== $next) { + $phpcsFile->addError($error, $i, 'SpaceAfterAs', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterAs', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($i + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContent($i, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($i + 1), ' '); + } + } + } + }//end if + }//end if + + if ($tokens[$i]['code'] === T_SEMICOLON) { + if ($tokens[($i - 1)]['code'] === T_WHITESPACE) { + $error = 'Expected no space before semicolon in trait import statement; %s found'; + $data = [$tokens[($i - 1)]['length']]; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeSemicolon', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($i - 1), ''); + } + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), ($closer - 1), true); + if ($next !== false && $tokens[$next]['line'] === $tokens[$i]['line']) { + $error = 'Each trait conflict resolution statement must be on a line by itself'; + $nextNonWs = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), ($closer - 1), true); + if ($nextNonWs !== $next) { + $phpcsFile->addError($error, $i, 'ConflictSameLine'); + } else { + $fix = $phpcsFile->addFixableError($error, $i, 'ConflictSameLine'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + if ($tokens[($i + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($i + 1), ''); + } + + $phpcsFile->fixer->addNewline($i); + $phpcsFile->fixer->endChangeset(); + } + } + } + }//end if + }//end for + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($closer - 1), ($opener + 1), true); + if ($prev !== false && $tokens[$prev]['line'] !== ($tokens[$closer]['line'] - 1)) { + $error = 'Closing brace must be on the line after the last trait conflict resolution statement'; + $prevNonWs = $phpcsFile->findPrevious(T_WHITESPACE, ($closer - 1), ($opener + 1), true); + if ($prevNonWs !== $prev) { + $phpcsFile->addError($error, $closer, 'SpaceBeforeClosingBrace'); + } else { + $fix = $phpcsFile->addFixableError($error, $closer, 'SpaceBeforeClosingBrace'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($closer - 1); $x > $prev; $x--) { + if ($tokens[$x]['line'] === $tokens[$closer]['line']) { + // Preserve indent. + continue; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addNewline($prev); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end processUseGroup() + + + /** + * Processes a single use statement. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processUseStatement(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $next = $phpcsFile->findNext([T_COMMA, T_SEMICOLON], ($stackPtr + 1)); + if ($next !== false && $tokens[$next]['code'] === T_COMMA) { + $error = 'Each imported trait must have its own "use" import statement'; + $fix = $phpcsFile->addFixableError($error, $next, 'MultipleImport'); + if ($fix === true) { + $padding = str_repeat(' ', ($tokens[$stackPtr]['column'] - 1)); + $phpcsFile->fixer->replaceToken($next, ';'.$phpcsFile->eolChar.$padding.'use '); + } + } + + }//end processUseStatement() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc new file mode 100644 index 0000000..fe3ee02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc @@ -0,0 +1,90 @@ +bar( + new class implements Bar { + // ... + }, +); + +foo(new class { +}); + +// Issue #3790: OpenBraceSameLine fixer should not remove open brace. +$instance = new class() extends SomeClass implements + SomeInterface{ + public function __construct() {} +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..4a6c5a1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.inc.fixed @@ -0,0 +1,93 @@ +bar( + new class implements Bar { + // ... + }, +); + +foo(new class { +}); + +// Issue #3790: OpenBraceSameLine fixer should not remove open brace. +$instance = new class () extends SomeClass implements + SomeInterface +{ + public function __construct() {} +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.php new file mode 100644 index 0000000..736d28c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/AnonClassDeclarationUnitTest.php @@ -0,0 +1,78 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the AnonClassDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\AnonClassDeclarationSniff + */ +class AnonClassDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 28 => 3, + 30 => 1, + 31 => 4, + 32 => 1, + 33 => 1, + 34 => 1, + 35 => 1, + 36 => 1, + 37 => 3, + 39 => 1, + 40 => 1, + 43 => 3, + 44 => 4, + 45 => 1, + 48 => 1, + 52 => 3, + 53 => 1, + 54 => 1, + 55 => 1, + 56 => 2, + 63 => 1, + 75 => 1, + 87 => 1, + 88 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc new file mode 100644 index 0000000..9fd1548 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc @@ -0,0 +1,47 @@ +bar(); +echo (new Foo)->bar(); +echo (new Foo((new Bar)->getBaz()))->bar(); +$foo = (new Foo)::$bar; + +echo (new Foo((new Bar//comment +)->getBaz(new Baz /* comment */)))->bar(); + +$foo = new $bar['a'](); +$foo = new $bar['a']['b'](); +$foo = new $bar['a'][$baz['a']['b']]['b'](); +$foo = new $bar['a'] [$baz['a']/* comment */ ['b']]['b']; + +$a = new self::$transport[$cap_string]; +$renderer = new $this->inline_diff_renderer; +$a = new ${$varHoldingClassName}; + +$class = new $obj?->classname(); +$class = new $obj?->classname; +$class = new ${$obj?->classname}; + +// Issue 3456. +// Anon classes should be skipped, even when there is an attribute between the new and the class keywords. +$anonWithAttribute = new #[SomeAttribute('summary')] class { + public const SOME_STUFF = 'foo'; +}; + +$foo = new parent(); +$foo = new parent; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc.fixed new file mode 100644 index 0000000..aa9d0c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.inc.fixed @@ -0,0 +1,47 @@ +bar(); +echo (new Foo())->bar(); +echo (new Foo((new Bar())->getBaz()))->bar(); +$foo = (new Foo())::$bar; + +echo (new Foo((new Bar()//comment +)->getBaz(new Baz() /* comment */)))->bar(); + +$foo = new $bar['a'](); +$foo = new $bar['a']['b'](); +$foo = new $bar['a'][$baz['a']['b']]['b'](); +$foo = new $bar['a'] [$baz['a']/* comment */ ['b']]['b'](); + +$a = new self::$transport[$cap_string](); +$renderer = new $this->inline_diff_renderer(); +$a = new ${$varHoldingClassName}(); + +$class = new $obj?->classname(); +$class = new $obj?->classname(); +$class = new ${$obj?->classname}(); + +// Issue 3456. +// Anon classes should be skipped, even when there is an attribute between the new and the class keywords. +$anonWithAttribute = new #[SomeAttribute('summary')] class { + public const SOME_STUFF = 'foo'; +}; + +$foo = new parent(); +$foo = new parent(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.php new file mode 100644 index 0000000..1eb233a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClassInstantiationUnitTest.php @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassInstantiation sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\ClassInstantiationSniff + */ +class ClassInstantiationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 4 => 1, + 9 => 1, + 11 => 1, + 14 => 1, + 16 => 1, + 20 => 1, + 21 => 1, + 22 => 1, + 24 => 1, + 25 => 1, + 30 => 1, + 32 => 1, + 33 => 1, + 34 => 1, + 37 => 1, + 38 => 1, + 47 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.inc new file mode 100644 index 0000000..2562d26 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.inc @@ -0,0 +1,52 @@ +bar( + $arg1, + function ($arg2) use ($var1) { + // body + }, + $arg3 +); + +$instance = new class extends \Foo implements \HandleableInterface { + // Class content +}; + +$app->get('/hello/{name}', function ($name) use ($app) { + return 'Hello ' . $app->escape($name); +}); + +enum Foo4 +{ + +}//end diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.php new file mode 100644 index 0000000..ba4be7a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/ClosingBraceUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClosingBrace sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\ClosingBraceSniff + */ +class ClosingBraceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 13 => 1, + 14 => 1, + 19 => 1, + 24 => 1, + 31 => 1, + 52 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/OpeningBraceSpaceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/OpeningBraceSpaceUnitTest.inc new file mode 100644 index 0000000..2c41bde --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Classes/OpeningBraceSpaceUnitTest.inc @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the OpeningBraceSpace sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\OpeningBraceSpaceSniff + */ +class OpeningBraceSpaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 10 => 1, + 18 => 1, + 24 => 1, + 34 => 1, + 41 => 1, + 55 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc new file mode 100644 index 0000000..4bc2ece --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc @@ -0,0 +1,131 @@ + 0 && $n < 10) + || ($n > 10 && $n < 20) + || ($n > 20 && $n < 30) +) { + return $n; +} + +if ( + ( + $expr1 + && $expr2 + && $expr3 + && $expr4 + && $expr5 + && $expr6 + ) + || ($n > 100 && $n < 200) + || ($n > 200 && $n < 300) +) { + return $n; +} + +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly first +if ( + $expr1 + && $expr2 + && ($expr3 + || $expr4) + && $expr5 +) { + // if body +} elseif ( + $expr1 && + ($expr3 || $expr4) + && $expr5 +) { + // elseif body +} elseif ( + $expr1 + && ($expr3 || $expr4) && + $expr5 +) { + // elseif body +} + +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly last +if ( + $expr1 + && $expr2 + && ($expr3 + || $expr4) + && $expr5 +) { + // if body +} elseif ( + $expr1 && + ($expr3 || $expr4) + && $expr5 +) { + // elseif body +} elseif ( + $expr1 + && ($expr3 || $expr4) && + $expr5 +) { + // elseif body +} + +if ( + ($value == 1 || + $value == 2) + && + ($value == 3 || + $value == 4) +) { + return 5; +} + +// Reset to default. +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly + +match ( + $expr1 + && $expr2 && + $expr3 +) { + // structure body +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc.fixed new file mode 100644 index 0000000..5f4d223 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.inc.fixed @@ -0,0 +1,141 @@ + 0 && $n < 10) + || ($n > 10 && $n < 20) + || ($n > 20 && $n < 30) +) { + return $n; +} + +if ( + ( + $expr1 + && $expr2 + && $expr3 + && $expr4 + && $expr5 + && $expr6 + ) + || ($n > 100 && $n < 200) + || ($n > 200 && $n < 300) +) { + return $n; +} + +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly first +if ( + $expr1 + && $expr2 + && ($expr3 + || $expr4) + && $expr5 +) { + // if body +} elseif ( + $expr1 + && ($expr3 + || $expr4) + && $expr5 +) { + // elseif body +} elseif ( + $expr1 + && ($expr3 + || $expr4) + && $expr5 +) { + // elseif body +} + +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly last +if ( + $expr1 && + $expr2 && + ($expr3 || + $expr4) && + $expr5 +) { + // if body +} elseif ( + $expr1 && + ($expr3 || + $expr4) && + $expr5 +) { + // elseif body +} elseif ( + $expr1 && + ($expr3 || + $expr4) && + $expr5 +) { + // elseif body +} + +if ( + ($value == 1 || + $value == 2) + && + ($value == 3 || + $value == 4) +) { + return 5; +} + +// Reset to default. +// phpcs:set PSR12.ControlStructures.BooleanOperatorPlacement allowOnly + +match ( + $expr1 + && $expr2 + && $expr3 +) { + // structure body +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.php new file mode 100644 index 0000000..f7adc00 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/BooleanOperatorPlacementUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the BooleanOperatorPlacement sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures\BooleanOperatorPlacementSniff + */ +class BooleanOperatorPlacementUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 10 => 1, + 16 => 1, + 28 => 1, + 34 => 1, + 75 => 1, + 81 => 1, + 90 => 1, + 98 => 1, + 104 => 1, + 125 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc new file mode 100644 index 0000000..9c037d6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc @@ -0,0 +1,100 @@ + $foo + /* + * A multi-line comment. + */ + && $foo === true + ) { + break; + } + +match ( + $expr1 && + $expr2 && + $expr3 + ) { + // structure body +}; + +match ($expr1 && +$expr2 && + $expr3) { + // structure body +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..7ea61b1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed @@ -0,0 +1,103 @@ + $foo + /* + * A multi-line comment. + */ + && $foo === true + ) { + break; + } + +match ( + $expr1 && + $expr2 && + $expr3 +) { + // structure body +}; + +match ( + $expr1 && + $expr2 && + $expr3 +) { + // structure body +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.php new file mode 100644 index 0000000..a3ada24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/ControlStructures/ControlStructureSpacingUnitTest.php @@ -0,0 +1,73 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ControlStructureSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures\ControlStructureSpacingSniff + */ +class ControlStructureSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 2, + 16 => 1, + 17 => 1, + 18 => 1, + 22 => 1, + 23 => 1, + 32 => 1, + 33 => 1, + 34 => 1, + 37 => 1, + 38 => 1, + 39 => 1, + 48 => 2, + 58 => 1, + 59 => 1, + 92 => 1, + 96 => 1, + 97 => 1, + 98 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/DeclareStatementUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/DeclareStatementUnitTest.inc new file mode 100644 index 0000000..f21daaf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/DeclareStatementUnitTest.inc @@ -0,0 +1,50 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DeclareStatement sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\DeclareStatementSniff + */ +class DeclareStatementUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 3 => 1, + 4 => 1, + 5 => 2, + 6 => 1, + 7 => 1, + 9 => 2, + 10 => 1, + 11 => 3, + 12 => 2, + 13 => 1, + 14 => 2, + 16 => 3, + 19 => 3, + 22 => 1, + 24 => 1, + 26 => 3, + 28 => 3, + 34 => 2, + 43 => 1, + 46 => 1, + 47 => 1, + 49 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.1.inc new file mode 100644 index 0000000..1298ed7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.1.inc @@ -0,0 +1,29 @@ + + +

    + + + +

    + + + + +

    Demo

    + + +
  • My page
  • +
  • Write
  • +
  • Sign out
  • + +
  • Sign in
  • + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.15.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.15.inc new file mode 100644 index 0000000..11102be --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.15.inc @@ -0,0 +1,5 @@ + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.16.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.16.inc new file mode 100644 index 0000000..5c3df1f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/FileHeaderUnitTest.16.inc @@ -0,0 +1,13 @@ + + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FileHeader sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\FileHeaderSniff + */ +class FileHeaderUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FileHeaderUnitTest.2.inc': + return [ + 1 => 1, + 6 => 1, + 7 => 1, + 18 => 1, + 20 => 1, + 24 => 1, + ]; + case 'FileHeaderUnitTest.3.inc': + return [ + 9 => 1, + 18 => 1, + ]; + case 'FileHeaderUnitTest.4.inc': + return [ + 1 => 1, + 2 => 1, + 3 => 1, + 7 => 1, + ]; + case 'FileHeaderUnitTest.5.inc': + return [4 => 1]; + case 'FileHeaderUnitTest.7.inc': + case 'FileHeaderUnitTest.10.inc': + case 'FileHeaderUnitTest.11.inc': + return [1 => 1]; + case 'FileHeaderUnitTest.12.inc': + return [4 => 2]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/ImportStatementUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/ImportStatementUnitTest.inc new file mode 100644 index 0000000..6d024ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/ImportStatementUnitTest.inc @@ -0,0 +1,26 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ImportStatement sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\ImportStatementSniff + */ +class ImportStatementUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 4 => 1, + 7 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.1.inc new file mode 100644 index 0000000..0dbdf01 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.1.inc @@ -0,0 +1,3 @@ + +hi diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.4.inc new file mode 100644 index 0000000..09be8fb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Files/OpenTagUnitTest.4.inc @@ -0,0 +1,2 @@ + + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the OpenTag sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\OpenTagSniff + */ +class OpenTagUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'OpenTagUnitTest.2.inc': + return [1 => 1]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/NullableTypeDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/NullableTypeDeclarationUnitTest.inc new file mode 100644 index 0000000..056d74c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/NullableTypeDeclarationUnitTest.inc @@ -0,0 +1,95 @@ + + * @copyright 2006-2018 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the NullableWhitespace sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\NullableTypeDeclarationSniff + */ +class NullableTypeDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + protected function getErrorList() + { + return [ + 23 => 1, + 24 => 1, + 25 => 1, + 30 => 1, + 31 => 1, + 32 => 1, + 43 => 2, + 48 => 1, + 50 => 1, + 51 => 1, + 53 => 1, + 57 => 2, + 58 => 2, + 59 => 2, + 87 => 1, + 90 => 1, + 91 => 1, + 95 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + protected function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc new file mode 100644 index 0000000..59ab1aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc @@ -0,0 +1,66 @@ + $arg; + +return (!$a ? [ new class { public function b(): c {} } ] : []); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..cd79f78 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.inc.fixed @@ -0,0 +1,62 @@ + $arg; + +return (!$a ? [ new class { public function b(): c {} } ] : []); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.php new file mode 100644 index 0000000..ce059e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Functions/ReturnTypeDeclarationUnitTest.php @@ -0,0 +1,66 @@ + + * @copyright 2006-2018 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ReturnTypeDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\ReturnTypeDeclarationSniff + */ +class ReturnTypeDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + protected function getErrorList() + { + return [ + 27 => 1, + 28 => 1, + 35 => 2, + 41 => 2, + 48 => 2, + 52 => 1, + 55 => 1, + 56 => 1, + 59 => 1, + 60 => 1, + 62 => 1, + 64 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + protected function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Keywords/ShortFormTypeKeywordsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Keywords/ShortFormTypeKeywordsUnitTest.inc new file mode 100644 index 0000000..6ce930d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Keywords/ShortFormTypeKeywordsUnitTest.inc @@ -0,0 +1,14 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Keywords; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ShortFormTypeKeywords sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Keywords\ShortFormTypeKeywordsSniff + */ +class ShortFormTypeKeywordsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 1, + 7 => 1, + 13 => 1, + 14 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Namespaces/CompoundNamespaceDepthUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Namespaces/CompoundNamespaceDepthUnitTest.inc new file mode 100644 index 0000000..3336fc2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Namespaces/CompoundNamespaceDepthUnitTest.inc @@ -0,0 +1,31 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Namespaces; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the CompoundNamespaceDepth sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Namespaces\CompoundNamespaceDepthSniff + */ +class CompoundNamespaceDepthUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 10 => 1, + 18 => 1, + 21 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc new file mode 100644 index 0000000..c067e6a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc @@ -0,0 +1,77 @@ + $b) { + $variable =$foo ? 'foo' :'bar'; + $variable.='text'.'text'; +} + +$foo+= $a&$b; +$foo = $a|$b; +$foo =$a^$b; +$foo = ~$a; +$foo *=$a<<$b; +$foo = $a>>$b; + +function foo(&$a,& $b) {} + +$foo = $a and$b; +$foo = $a or $b; +$foo = $a xor$b; +$foo = !$a; +$foo = $a&&$b; +$foo = $a||$b; + +$foo = $a instanceof Foo; +$foo = $a instanceof$b; + +$foo .= 'hi' + .= 'there'; + +$foo .= 'hi' +.= 'there'; + +$foo .= 'hi' // comment +.= 'there'; + +$foo/*comment*/=/*comment*/$a/*comment*/and/*comment*/$b; + +$foo .=//comment +'string' .=/*comment*/ +'string'; + +$foo = $foo ?: 'bar'; +$foo = $foo?:'bar'; + +try { +} catch (ExceptionType1|ExceptionType2 $e) { +} + +if (strpos($tokenContent, 'b"') === 0 && substr($tokenContent, -1) === '"') {} + +$oldConstructorPos = +1; +return -$content; + +function name($a = -1) {} + +$a =& $ref; +$a = [ 'a' => &$something ]; + +$fn = fn(array &$one) => 1; +$fn = fn(array & $one) => 1; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +function issue3267(string|int ...$values) {} + +function setDefault(#[ImportValue( + constraints: [ + [ + Assert\Type::class, + ['type' => 'bool'], + ], + ] + )] ?bool $value = null): void + { + // Do something + } diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..7676429 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.inc.fixed @@ -0,0 +1,77 @@ + $b) { + $variable = $foo ? 'foo' : 'bar'; + $variable .= 'text' . 'text'; +} + +$foo += $a & $b; +$foo = $a | $b; +$foo = $a ^ $b; +$foo = ~$a; +$foo *= $a << $b; +$foo = $a >> $b; + +function foo(&$a,& $b) {} + +$foo = $a and $b; +$foo = $a or $b; +$foo = $a xor $b; +$foo = !$a; +$foo = $a && $b; +$foo = $a || $b; + +$foo = $a instanceof Foo; +$foo = $a instanceof $b; + +$foo .= 'hi' + .= 'there'; + +$foo .= 'hi' +.= 'there'; + +$foo .= 'hi' // comment +.= 'there'; + +$foo/*comment*/ = /*comment*/$a/*comment*/ and /*comment*/$b; + +$foo .= //comment +'string' .= /*comment*/ +'string'; + +$foo = $foo ?: 'bar'; +$foo = $foo ?: 'bar'; + +try { +} catch (ExceptionType1 | ExceptionType2 $e) { +} + +if (strpos($tokenContent, 'b"') === 0 && substr($tokenContent, -1) === '"') {} + +$oldConstructorPos = +1; +return -$content; + +function name($a = -1) {} + +$a =& $ref; +$a = [ 'a' => &$something ]; + +$fn = fn(array &$one) => 1; +$fn = fn(array & $one) => 1; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +function issue3267(string|int ...$values) {} + +function setDefault(#[ImportValue( + constraints: [ + [ + Assert\Type::class, + ['type' => 'bool'], + ], + ] + )] ?bool $value = null): void + { + // Do something + } diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.php new file mode 100644 index 0000000..5b17f76 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Operators/OperatorSpacingUnitTest.php @@ -0,0 +1,74 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Operators; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the OperatorSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff + */ +class OperatorSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 3 => 2, + 4 => 1, + 5 => 2, + 6 => 4, + 9 => 3, + 10 => 2, + 11 => 3, + 13 => 3, + 14 => 2, + 18 => 1, + 20 => 1, + 22 => 2, + 23 => 2, + 26 => 1, + 37 => 4, + 39 => 1, + 40 => 1, + 44 => 2, + 47 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Properties/ConstantVisibilityUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Properties/ConstantVisibilityUnitTest.inc new file mode 100644 index 0000000..84ea24b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Properties/ConstantVisibilityUnitTest.inc @@ -0,0 +1,22 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Properties; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ConstantVisibility sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Properties\ConstantVisibilitySniff + */ +class ConstantVisibilityUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 4 => 1, + 12 => 1, + 21 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Traits/UseDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Traits/UseDeclarationUnitTest.inc new file mode 100644 index 0000000..152121c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests/Traits/UseDeclarationUnitTest.inc @@ -0,0 +1,221 @@ + + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR12\Tests\Traits; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the UseDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR12\Sniffs\Traits\UseDeclarationSniff + */ +class UseDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 15 => 1, + 29 => 2, + 30 => 1, + 42 => 1, + 57 => 4, + 59 => 3, + 61 => 1, + 63 => 5, + 65 => 1, + 71 => 1, + 73 => 2, + 76 => 1, + 86 => 2, + 103 => 1, + 112 => 1, + 122 => 1, + 132 => 1, + 157 => 1, + 165 => 1, + 170 => 1, + 208 => 1, + 219 => 3, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/ruleset.xml new file mode 100644 index 0000000..a631fed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR12/ruleset.xml @@ -0,0 +1,348 @@ + + + The PSR-12 coding standard. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + error + Method name "%s" must not be prefixed with an underscore to indicate visibility + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + + + + + + + + + + + + + + + 0 + + + 0 + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/ClassDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/ClassDeclarationStandard.xml new file mode 100644 index 0000000..4e56bc0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/ClassDeclarationStandard.xml @@ -0,0 +1,23 @@ + + + + + + + class Foo +{ +} + ]]> + + + class Foo +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/PropertyDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/PropertyDeclarationStandard.xml new file mode 100644 index 0000000..042c0c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/PropertyDeclarationStandard.xml @@ -0,0 +1,81 @@ + + + + + + + bar; +} + ]]> + + + _bar; +} + ]]> + + + + + private $bar; +} + ]]> + + + var $bar; +} + ]]> + + + + + + + + $bar, $baz; +} + ]]> + + + + + static $bar; + private $baz; +} + ]]> + + + static protected $bar; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ControlStructureSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ControlStructureSpacingStandard.xml new file mode 100644 index 0000000..dcbe98f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ControlStructureSpacingStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $foo) { + $var = 1; +} + ]]> + + + $foo ) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ElseIfDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ElseIfDeclarationStandard.xml new file mode 100644 index 0000000..a22dd17 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ElseIfDeclarationStandard.xml @@ -0,0 +1,27 @@ + + + + + + + elseif ($bar) { + $var = 2; +} + ]]> + + + else if ($bar) { + $var = 2; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/SwitchDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/SwitchDeclarationStandard.xml new file mode 100644 index 0000000..1d6d053 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/SwitchDeclarationStandard.xml @@ -0,0 +1,104 @@ + + + + + + + case 'bar': + break; +} + ]]> + + + case 'bar': + break; +} + ]]> + + + + + 'bar': + break; +} + ]]> + + + 'bar': + break; +} + ]]> + + + + + : + break; + default: + break; +} + ]]> + + + : + break; + default : + break; +} + ]]> + + + + + break; +} + ]]> + + + break; +} + ]]> + + + + + // no break + default: + break; +} + ]]> + + + : + break; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/ClosingTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/ClosingTagStandard.xml new file mode 100644 index 0000000..60d5e7f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/ClosingTagStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + ]]> + + + ?> + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/EndFileNewlineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/EndFileNewlineStandard.xml new file mode 100644 index 0000000..d6d3aad --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/EndFileNewlineStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionCallSignatureStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionCallSignatureStandard.xml new file mode 100644 index 0000000..257bcab --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionCallSignatureStandard.xml @@ -0,0 +1,107 @@ + + + + + + + ($bar, $baz); + ]]> + + + ( $bar, $baz ); + ]]> + + + + + $bar, + $baz +); + ]]> + + + $bar, + $baz +); + ]]> + + + + + ); + ]]> + + + ); + ]]> + + + + + $bar, + $baz +); + ]]> + + + $bar, + $baz +); + ]]> + + + + + $baz +); + ]]> + + + $baz +); + ]]> + + + + + + + + + $baz +); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionClosingBraceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionClosingBraceStandard.xml new file mode 100644 index 0000000..3b1b655 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/FunctionClosingBraceStandard.xml @@ -0,0 +1,26 @@ + + + + + + + } + ]]> + + + +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/MethodDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/MethodDeclarationStandard.xml new file mode 100644 index 0000000..e45469e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/MethodDeclarationStandard.xml @@ -0,0 +1,51 @@ + + + + + + + bar() + { + } +} + ]]> + + + _bar() + { + } +} + ]]> + + + + + final public static function bar() + { + } +} + ]]> + + + static public final function bar() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/NamespaceDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/NamespaceDeclarationStandard.xml new file mode 100644 index 0000000..1f4d389 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/NamespaceDeclarationStandard.xml @@ -0,0 +1,22 @@ + + + + + + + +use \Baz; + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/UseDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/UseDeclarationStandard.xml new file mode 100644 index 0000000..4082603 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/UseDeclarationStandard.xml @@ -0,0 +1,57 @@ + + + + + + + + + + \Foo, \Bar; + ]]> + + + + + + + + + + + + + +class Baz +{ +} + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php new file mode 100644 index 0000000..6d59b89 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php @@ -0,0 +1,529 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\PEAR\Sniffs\Classes\ClassDeclarationSniff as PEARClassDeclarationSniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassDeclarationSniff extends PEARClassDeclarationSniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // We want all the errors from the PEAR standard, plus some of our own. + parent::process($phpcsFile, $stackPtr); + + // Just in case. + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + return; + } + + $this->processOpen($phpcsFile, $stackPtr); + $this->processClose($phpcsFile, $stackPtr); + + }//end process() + + + /** + * Processes the opening section of a class declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processOpen(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $stackPtrType = strtolower($tokens[$stackPtr]['content']); + + // Check alignment of the keyword and braces. + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + $prevContent = $tokens[($stackPtr - 1)]['content']; + if ($prevContent !== $phpcsFile->eolChar) { + $blankSpace = substr($prevContent, strpos($prevContent, $phpcsFile->eolChar)); + $spaces = strlen($blankSpace); + + if (in_array($tokens[($stackPtr - 2)]['code'], [T_ABSTRACT, T_FINAL, T_READONLY], true) === true + && $spaces !== 1 + ) { + $prevContent = strtolower($tokens[($stackPtr - 2)]['content']); + $error = 'Expected 1 space between %s and %s keywords; %s found'; + $data = [ + $prevContent, + $stackPtrType, + $spaces, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeKeyword', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + } + } else if ($tokens[($stackPtr - 2)]['code'] === T_ABSTRACT + || $tokens[($stackPtr - 2)]['code'] === T_FINAL + || $tokens[($stackPtr - 2)]['code'] === T_READONLY + ) { + $prevContent = strtolower($tokens[($stackPtr - 2)]['content']); + $error = 'Expected 1 space between %s and %s keywords; newline found'; + $data = [ + $prevContent, + $stackPtrType, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NewlineBeforeKeyword', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + }//end if + }//end if + + // We'll need the indent of the class/interface declaration for later. + $classIndent = 0; + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { + continue; + } + + // We changed lines. + if ($tokens[($i + 1)]['code'] === T_WHITESPACE) { + $classIndent = $tokens[($i + 1)]['length']; + } + + break; + } + + $className = null; + $checkSpacing = true; + + if ($tokens[$stackPtr]['code'] !== T_ANON_CLASS) { + $className = $phpcsFile->findNext(T_STRING, $stackPtr); + } else { + // Ignore the spacing check if this is a simple anon class. + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($next === $tokens[$stackPtr]['scope_opener'] + && $tokens[$next]['line'] > $tokens[$stackPtr]['line'] + ) { + $checkSpacing = false; + } + } + + if ($checkSpacing === true) { + // Spacing of the keyword. + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $gap = 0; + } else if ($tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line']) { + $gap = 'newline'; + } else { + $gap = $tokens[($stackPtr + 1)]['length']; + } + + if ($gap !== 1) { + $error = 'Expected 1 space after %s keyword; %s found'; + $data = [ + $stackPtrType, + $gap, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterKeyword', $data); + if ($fix === true) { + if ($gap === 0) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } else { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } + }//end if + + // Check after the class/interface name. + if ($className !== null + && $tokens[($className + 2)]['line'] === $tokens[$className]['line'] + ) { + $gap = $tokens[($className + 1)]['content']; + if (strlen($gap) !== 1) { + $found = strlen($gap); + $error = 'Expected 1 space after %s name; %s found'; + $data = [ + $stackPtrType, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $className, 'SpaceAfterName', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($className + 1), ' '); + } + } + } + + $openingBrace = $tokens[$stackPtr]['scope_opener']; + + // Check positions of the extends and implements keywords. + $compareToken = $stackPtr; + $compareType = 'name'; + if ($tokens[$stackPtr]['code'] === T_ANON_CLASS) { + if (isset($tokens[$stackPtr]['parenthesis_opener']) === true) { + $compareToken = $tokens[$stackPtr]['parenthesis_closer']; + $compareType = 'closing parenthesis'; + } else { + $compareType = 'keyword'; + } + } + + foreach (['extends', 'implements'] as $keywordType) { + $keyword = $phpcsFile->findNext(constant('T_'.strtoupper($keywordType)), ($compareToken + 1), $openingBrace); + if ($keyword !== false) { + if ($tokens[$keyword]['line'] !== $tokens[$compareToken]['line']) { + $error = 'The '.$keywordType.' keyword must be on the same line as the %s '.$compareType; + $data = [$stackPtrType]; + $fix = $phpcsFile->addFixableError($error, $keyword, ucfirst($keywordType).'Line', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $comments = []; + + for ($i = ($compareToken + 1); $i < $keyword; ++$i) { + if ($tokens[$i]['code'] === T_COMMENT) { + $comments[] = trim($tokens[$i]['content']); + } + + if ($tokens[$i]['code'] === T_WHITESPACE + || $tokens[$i]['code'] === T_COMMENT + ) { + $phpcsFile->fixer->replaceToken($i, ' '); + } + } + + $phpcsFile->fixer->addContent($compareToken, ' '); + if (empty($comments) === false) { + $i = $keyword; + while ($tokens[($i + 1)]['line'] === $tokens[$keyword]['line']) { + ++$i; + } + + $phpcsFile->fixer->addContentBefore($i, ' '.implode(' ', $comments)); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + } else { + // Check the whitespace before. Whitespace after is checked + // later by looking at the whitespace before the first class name + // in the list. + $gap = $tokens[($keyword - 1)]['length']; + if ($gap !== 1) { + $error = 'Expected 1 space before '.$keywordType.' keyword; %s found'; + $data = [$gap]; + $fix = $phpcsFile->addFixableError($error, $keyword, 'SpaceBefore'.ucfirst($keywordType), $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($keyword - 1), ' '); + } + } + }//end if + }//end if + }//end foreach + + // Check each of the extends/implements class names. If the extends/implements + // keyword is the last content on the line, it means we need to check for + // the multi-line format, so we do not include the class names + // from the extends/implements list in the following check. + // Note that classes can only extend one other class, so they can't use a + // multi-line extends format, whereas an interface can extend multiple + // other interfaces, and so uses a multi-line extends format. + if ($tokens[$stackPtr]['code'] === T_INTERFACE) { + $keywordTokenType = T_EXTENDS; + } else { + $keywordTokenType = T_IMPLEMENTS; + } + + $implements = $phpcsFile->findNext($keywordTokenType, ($stackPtr + 1), $openingBrace); + $multiLineImplements = false; + if ($implements !== false) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($openingBrace - 1), $implements, true); + if ($tokens[$prev]['line'] !== $tokens[$implements]['line']) { + $multiLineImplements = true; + } + } + + $find = [ + T_STRING, + $keywordTokenType, + ]; + + if ($className !== null) { + $start = $className; + } else if (isset($tokens[$stackPtr]['parenthesis_closer']) === true) { + $start = $tokens[$stackPtr]['parenthesis_closer']; + } else { + $start = $stackPtr; + } + + $classNames = []; + $nextClass = $phpcsFile->findNext($find, ($start + 2), ($openingBrace - 1)); + while ($nextClass !== false) { + $classNames[] = $nextClass; + $nextClass = $phpcsFile->findNext($find, ($nextClass + 1), ($openingBrace - 1)); + } + + $classCount = count($classNames); + $checkingImplements = false; + $implementsToken = null; + foreach ($classNames as $n => $className) { + if ($tokens[$className]['code'] === $keywordTokenType) { + $checkingImplements = true; + $implementsToken = $className; + + continue; + } + + if ($checkingImplements === true + && $multiLineImplements === true + && ($tokens[($className - 1)]['code'] !== T_NS_SEPARATOR + || $tokens[($className - 2)]['code'] !== T_STRING) + ) { + $prev = $phpcsFile->findPrevious( + [ + T_NS_SEPARATOR, + T_WHITESPACE, + ], + ($className - 1), + $implements, + true + ); + + if ($prev === $implementsToken && $tokens[$className]['line'] !== ($tokens[$prev]['line'] + 1)) { + if ($keywordTokenType === T_EXTENDS) { + $error = 'The first item in a multi-line extends list must be on the line following the extends keyword'; + $fix = $phpcsFile->addFixableError($error, $className, 'FirstExtendsInterfaceSameLine'); + } else { + $error = 'The first item in a multi-line implements list must be on the line following the implements keyword'; + $fix = $phpcsFile->addFixableError($error, $className, 'FirstInterfaceSameLine'); + } + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $className; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addNewline($prev); + $phpcsFile->fixer->endChangeset(); + } + } else if ($tokens[$prev]['line'] !== ($tokens[$className]['line'] - 1)) { + if ($keywordTokenType === T_EXTENDS) { + $error = 'Only one interface may be specified per line in a multi-line extends declaration'; + $fix = $phpcsFile->addFixableError($error, $className, 'ExtendsInterfaceSameLine'); + } else { + $error = 'Only one interface may be specified per line in a multi-line implements declaration'; + $fix = $phpcsFile->addFixableError($error, $className, 'InterfaceSameLine'); + } + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $className; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addNewline($prev); + $phpcsFile->fixer->endChangeset(); + } + } else { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($className - 1), $implements); + if ($tokens[$prev]['line'] !== $tokens[$className]['line']) { + $found = 0; + } else { + $found = $tokens[$prev]['length']; + } + + $expected = ($classIndent + $this->indent); + if ($found !== $expected) { + $error = 'Expected %s spaces before interface name; %s found'; + $data = [ + $expected, + $found, + ]; + $fix = $phpcsFile->addFixableError($error, $className, 'InterfaceWrongIndent', $data); + if ($fix === true) { + $padding = str_repeat(' ', $expected); + if ($found === 0) { + $phpcsFile->fixer->addContent($prev, $padding); + } else { + $phpcsFile->fixer->replaceToken($prev, $padding); + } + } + } + }//end if + } else if ($tokens[($className - 1)]['code'] !== T_NS_SEPARATOR + || $tokens[($className - 2)]['code'] !== T_STRING + ) { + // Not part of a longer fully qualified class name. + if ($tokens[($className - 1)]['code'] === T_COMMA + || ($tokens[($className - 1)]['code'] === T_NS_SEPARATOR + && $tokens[($className - 2)]['code'] === T_COMMA) + ) { + $error = 'Expected 1 space before "%s"; 0 found'; + $data = [$tokens[$className]['content']]; + $fix = $phpcsFile->addFixableError($error, ($nextComma + 1), 'NoSpaceBeforeName', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore(($nextComma + 1), ' '); + } + } else { + if ($tokens[($className - 1)]['code'] === T_NS_SEPARATOR) { + $prev = ($className - 2); + } else { + $prev = ($className - 1); + } + + $last = $phpcsFile->findPrevious(T_WHITESPACE, $prev, null, true); + $content = $phpcsFile->getTokensAsString(($last + 1), ($prev - $last)); + if ($content !== ' ') { + $found = strlen($content); + + $error = 'Expected 1 space before "%s"; %s found'; + $data = [ + $tokens[$className]['content'], + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $className, 'SpaceBeforeName', $data); + if ($fix === true) { + if ($tokens[$prev]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($prev, ' '); + while ($tokens[--$prev]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($prev, ' '); + } + + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->addContent($prev, ' '); + } + } + }//end if + }//end if + }//end if + + if ($checkingImplements === true + && $tokens[($className + 1)]['code'] !== T_NS_SEPARATOR + && $tokens[($className + 1)]['code'] !== T_COMMA + ) { + if ($n !== ($classCount - 1)) { + // This is not the last class name, and the comma + // is not where we expect it to be. + if ($tokens[($className + 2)]['code'] !== $keywordTokenType) { + $error = 'Expected 0 spaces between "%s" and comma; %s found'; + $data = [ + $tokens[$className]['content'], + $tokens[($className + 1)]['length'], + ]; + + $fix = $phpcsFile->addFixableError($error, $className, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($className + 1), ''); + } + } + } + + $nextComma = $phpcsFile->findNext(T_COMMA, $className); + } else { + $nextComma = ($className + 1); + }//end if + }//end foreach + + }//end processOpen() + + + /** + * Processes the closing section of a class declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processClose(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Check that the closing brace comes right after the code body. + $closeBrace = $tokens[$stackPtr]['scope_closer']; + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBrace - 1), null, true); + if ($prevContent !== $tokens[$stackPtr]['scope_opener'] + && $tokens[$prevContent]['line'] !== ($tokens[$closeBrace]['line'] - 1) + ) { + $error = 'The closing brace for the %s must go on the next line after the body'; + $data = [$tokens[$stackPtr]['content']]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'CloseBraceAfterBody', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prevContent + 1); $tokens[$i]['line'] !== $tokens[$closeBrace]['line']; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + if (strpos($tokens[$prevContent]['content'], $phpcsFile->eolChar) === false) { + $phpcsFile->fixer->addNewline($prevContent); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + if ($tokens[$stackPtr]['code'] !== T_ANON_CLASS) { + // Check the closing brace is on it's own line, but allow + // for comments like "//end class". + $ignoreTokens = Tokens::$phpcsCommentTokens; + $ignoreTokens[] = T_WHITESPACE; + $ignoreTokens[] = T_COMMENT; + $ignoreTokens[] = T_SEMICOLON; + $ignoreTokens[] = T_COMMA; + $nextContent = $phpcsFile->findNext($ignoreTokens, ($closeBrace + 1), null, true); + if ($tokens[$nextContent]['content'] !== $phpcsFile->eolChar + && $tokens[$nextContent]['line'] === $tokens[$closeBrace]['line'] + ) { + $type = strtolower($tokens[$stackPtr]['content']); + $error = 'Closing %s brace must be on a line by itself'; + $data = [$type]; + $phpcsFile->addError($error, $closeBrace, 'CloseBraceSameLine', $data); + } + } + + }//end processClose() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/PropertyDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/PropertyDeclarationSniff.php new file mode 100644 index 0000000..550e045 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/PropertyDeclarationSniff.php @@ -0,0 +1,225 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; +use PHP_CodeSniffer\Util\Tokens; + +class PropertyDeclarationSniff extends AbstractVariableSniff +{ + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['content'][1] === '_') { + $error = 'Property name "%s" should not be prefixed with an underscore to indicate visibility'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addWarning($error, $stackPtr, 'Underscore', $data); + } + + // Detect multiple properties defined at the same time. Throw an error + // for this, but also only process the first property in the list so we don't + // repeat errors. + $find = Tokens::$scopeModifiers; + $find[] = T_VARIABLE; + $find[] = T_VAR; + $find[] = T_READONLY; + $find[] = T_SEMICOLON; + $find[] = T_OPEN_CURLY_BRACKET; + + $prev = $phpcsFile->findPrevious($find, ($stackPtr - 1)); + if ($tokens[$prev]['code'] === T_VARIABLE) { + return; + } + + if ($tokens[$prev]['code'] === T_VAR) { + $error = 'The var keyword must not be used to declare a property'; + $phpcsFile->addError($error, $stackPtr, 'VarUsed'); + } + + $next = $phpcsFile->findNext([T_VARIABLE, T_SEMICOLON], ($stackPtr + 1)); + if ($next !== false && $tokens[$next]['code'] === T_VARIABLE) { + $error = 'There must not be more than one property declared per statement'; + $phpcsFile->addError($error, $stackPtr, 'Multiple'); + } + + try { + $propertyInfo = $phpcsFile->getMemberProperties($stackPtr); + if (empty($propertyInfo) === true) { + return; + } + } catch (\Exception $e) { + // Turns out not to be a property after all. + return; + } + + if ($propertyInfo['type'] !== '') { + $typeToken = $propertyInfo['type_end_token']; + $error = 'There must be 1 space after the property type declaration; %s found'; + if ($tokens[($typeToken + 1)]['code'] !== T_WHITESPACE) { + $data = ['0']; + $fix = $phpcsFile->addFixableError($error, $typeToken, 'SpacingAfterType', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($typeToken, ' '); + } + } else if ($tokens[($typeToken + 1)]['content'] !== ' ') { + $next = $phpcsFile->findNext(T_WHITESPACE, ($typeToken + 1), null, true); + if ($tokens[$next]['line'] !== $tokens[$typeToken]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($typeToken + 1)]['length']; + } + + $data = [$found]; + + $nextNonWs = $phpcsFile->findNext(Tokens::$emptyTokens, ($typeToken + 1), null, true); + if ($nextNonWs !== $next) { + $phpcsFile->addError($error, $typeToken, 'SpacingAfterType', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $typeToken, 'SpacingAfterType', $data); + if ($fix === true) { + if ($found === 'newline') { + $phpcsFile->fixer->beginChangeset(); + for ($x = ($typeToken + 1); $x < $next; $x++) { + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addContent($typeToken, ' '); + $phpcsFile->fixer->endChangeset(); + } else { + $phpcsFile->fixer->replaceToken(($typeToken + 1), ' '); + } + } + } + }//end if + }//end if + + if ($propertyInfo['scope_specified'] === false) { + $error = 'Visibility must be declared on property "%s"'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addError($error, $stackPtr, 'ScopeMissing', $data); + } + + /* + * Note: per PSR-PER section 4.6, the order should be: + * - Inheritance modifier: `abstract` or `final`. + * - Visibility modifier: `public`, `protected`, or `private`. + * - Scope modifier: `static`. + * - Mutation modifier: `readonly`. + * - Type declaration. + * - Name. + * + * Ref: https://www.php-fig.org/per/coding-style/#46-modifier-keywords + * + * At this time (PHP 8.2), inheritance modifiers cannot be applied to properties and + * the `static` and `readonly` modifiers are mutually exclusive and cannot be used together. + * + * Based on that, the below modifier keyword order checks are sufficient (for now). + */ + + if ($propertyInfo['scope_specified'] === true && $propertyInfo['is_static'] === true) { + $scopePtr = $phpcsFile->findPrevious(Tokens::$scopeModifiers, ($stackPtr - 1)); + $staticPtr = $phpcsFile->findPrevious(T_STATIC, ($stackPtr - 1)); + if ($scopePtr > $staticPtr) { + $error = 'The static declaration must come after the visibility declaration'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'StaticBeforeVisibility'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($scopePtr + 1); $scopePtr < $stackPtr; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken($scopePtr, ''); + $phpcsFile->fixer->addContentBefore($staticPtr, $propertyInfo['scope'].' '); + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + if ($propertyInfo['scope_specified'] === true && $propertyInfo['is_readonly'] === true) { + $scopePtr = $phpcsFile->findPrevious(Tokens::$scopeModifiers, ($stackPtr - 1)); + $readonlyPtr = $phpcsFile->findPrevious(T_READONLY, ($stackPtr - 1)); + if ($scopePtr > $readonlyPtr) { + $error = 'The readonly declaration must come after the visibility declaration'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ReadonlyBeforeVisibility'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($scopePtr + 1); $scopePtr < $stackPtr; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken($scopePtr, ''); + $phpcsFile->fixer->addContentBefore($readonlyPtr, $propertyInfo['scope'].' '); + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end processMemberVar() + + + /** + * Processes normal variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariable() + + + /** + * Processes variables in double quoted strings. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ControlStructureSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ControlStructureSpacingSniff.php new file mode 100644 index 0000000..d855dbd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ControlStructureSpacingSniff.php @@ -0,0 +1,141 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ControlStructureSpacingSniff implements Sniff +{ + + /** + * How many spaces should follow the opening bracket. + * + * @var integer + */ + public $requiredSpacesAfterOpen = 0; + + /** + * How many spaces should precede the closing bracket. + * + * @var integer + */ + public $requiredSpacesBeforeClose = 0; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_WHILE, + T_FOREACH, + T_FOR, + T_SWITCH, + T_ELSEIF, + T_CATCH, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $this->requiredSpacesAfterOpen = (int) $this->requiredSpacesAfterOpen; + $this->requiredSpacesBeforeClose = (int) $this->requiredSpacesBeforeClose; + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + ) { + return; + } + + $parenOpener = $tokens[$stackPtr]['parenthesis_opener']; + $parenCloser = $tokens[$stackPtr]['parenthesis_closer']; + $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($parenOpener + 1), null, true); + if (in_array($tokens[$nextContent]['code'], Tokens::$commentTokens, true) === false) { + $spaceAfterOpen = 0; + if ($tokens[($parenOpener + 1)]['code'] === T_WHITESPACE) { + if (strpos($tokens[($parenOpener + 1)]['content'], $phpcsFile->eolChar) !== false) { + $spaceAfterOpen = 'newline'; + } else { + $spaceAfterOpen = $tokens[($parenOpener + 1)]['length']; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Spaces after control structure open parenthesis', $spaceAfterOpen); + + if ($spaceAfterOpen !== $this->requiredSpacesAfterOpen) { + $error = 'Expected %s spaces after opening bracket; %s found'; + $data = [ + $this->requiredSpacesAfterOpen, + $spaceAfterOpen, + ]; + $fix = $phpcsFile->addFixableError($error, ($parenOpener + 1), 'SpacingAfterOpenBrace', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesAfterOpen); + if ($spaceAfterOpen === 0) { + $phpcsFile->fixer->addContent($parenOpener, $padding); + } else if ($spaceAfterOpen === 'newline') { + $phpcsFile->fixer->replaceToken(($parenOpener + 1), ''); + } else { + $phpcsFile->fixer->replaceToken(($parenOpener + 1), $padding); + } + } + } + }//end if + + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($parenCloser - 1), $parenOpener, true); + if ($tokens[$prev]['line'] === $tokens[$parenCloser]['line']) { + $spaceBeforeClose = 0; + if ($tokens[($parenCloser - 1)]['code'] === T_WHITESPACE) { + $spaceBeforeClose = strlen(ltrim($tokens[($parenCloser - 1)]['content'], $phpcsFile->eolChar)); + } + + $phpcsFile->recordMetric($stackPtr, 'Spaces before control structure close parenthesis', $spaceBeforeClose); + + if ($spaceBeforeClose !== $this->requiredSpacesBeforeClose) { + $error = 'Expected %s spaces before closing bracket; %s found'; + $data = [ + $this->requiredSpacesBeforeClose, + $spaceBeforeClose, + ]; + $fix = $phpcsFile->addFixableError($error, ($parenCloser - 1), 'SpaceBeforeCloseBrace', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesBeforeClose); + if ($spaceBeforeClose === 0) { + $phpcsFile->fixer->addContentBefore($parenCloser, $padding); + } else { + $phpcsFile->fixer->replaceToken(($parenCloser - 1), $padding); + } + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ElseIfDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ElseIfDeclarationSniff.php new file mode 100644 index 0000000..7f5e97c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ElseIfDeclarationSniff.php @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ElseIfDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_ELSE, + T_ELSEIF, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_ELSEIF) { + $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'elseif'); + return; + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_IF) { + $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'else if'); + $error = 'Usage of ELSE IF is discouraged; use ELSEIF instead'; + $fix = $phpcsFile->addFixableWarning($error, $stackPtr, 'NotAllowed'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($stackPtr, 'elseif'); + for ($i = ($stackPtr + 1); $i <= $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php new file mode 100644 index 0000000..4b3b5ad --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php @@ -0,0 +1,396 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SwitchDeclarationSniff implements Sniff +{ + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_SWITCH]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // We can't process SWITCH statements unless we know where they start and end. + if (isset($tokens[$stackPtr]['scope_opener']) === false + || isset($tokens[$stackPtr]['scope_closer']) === false + ) { + return; + } + + $switch = $tokens[$stackPtr]; + $nextCase = $stackPtr; + $caseAlignment = ($switch['column'] + $this->indent); + + while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $switch['scope_closer'])) !== false) { + if ($tokens[$nextCase]['code'] === T_DEFAULT) { + $type = 'default'; + } else { + $type = 'case'; + } + + if ($tokens[$nextCase]['content'] !== strtolower($tokens[$nextCase]['content'])) { + $expected = strtolower($tokens[$nextCase]['content']); + $error = strtoupper($type).' keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + $expected, + $tokens[$nextCase]['content'], + ]; + + $fix = $phpcsFile->addFixableError($error, $nextCase, $type.'NotLower', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($nextCase, $expected); + } + } + + if ($type === 'case' + && ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE + || $tokens[($nextCase + 1)]['content'] !== ' ') + ) { + $error = 'CASE keyword must be followed by a single space'; + $fix = $phpcsFile->addFixableError($error, $nextCase, 'SpacingAfterCase'); + if ($fix === true) { + if ($tokens[($nextCase + 1)]['code'] !== T_WHITESPACE) { + $phpcsFile->fixer->addContent($nextCase, ' '); + } else { + $phpcsFile->fixer->replaceToken(($nextCase + 1), ' '); + } + } + } + + $opener = $tokens[$nextCase]['scope_opener']; + $nextCloser = $tokens[$nextCase]['scope_closer']; + if ($tokens[$opener]['code'] === T_COLON) { + if ($tokens[($opener - 1)]['code'] === T_WHITESPACE) { + $error = 'There must be no space before the colon in a '.strtoupper($type).' statement'; + $fix = $phpcsFile->addFixableError($error, $nextCase, 'SpaceBeforeColon'.strtoupper($type)); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($opener - 1), ''); + } + } + + for ($next = ($opener + 1); $next < $nextCloser; $next++) { + if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === false + || (isset(Tokens::$commentTokens[$tokens[$next]['code']]) === true + && $tokens[$next]['line'] !== $tokens[$opener]['line']) + ) { + break; + } + } + + if ($tokens[$next]['line'] !== ($tokens[$opener]['line'] + 1)) { + $error = 'The '.strtoupper($type).' body must start on the line following the statement'; + $fix = $phpcsFile->addFixableError($error, $nextCase, 'BodyOnNextLine'.strtoupper($type)); + if ($fix === true) { + if ($tokens[$next]['line'] === $tokens[$opener]['line']) { + $padding = str_repeat(' ', ($caseAlignment + $this->indent - 1)); + $phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar.$padding); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($opener + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$opener]['line']) { + // Ignore trailing comments. + continue; + } + + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + if ($tokens[$nextCloser]['scope_condition'] === $nextCase) { + // Only need to check some things once, even if the + // closer is shared between multiple case statements, or even + // the default case. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCloser - 1), $nextCase, true); + if ($tokens[$prev]['line'] === $tokens[$nextCloser]['line']) { + $error = 'Terminating statement must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $nextCloser, 'BreakNotNewLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewLine($prev); + $phpcsFile->fixer->replaceToken($nextCloser, trim($tokens[$nextCloser]['content'])); + } + } else { + $diff = ($tokens[$nextCase]['column'] + $this->indent - $tokens[$nextCloser]['column']); + if ($diff !== 0) { + $error = 'Terminating statement must be indented to the same level as the CASE body'; + $fix = $phpcsFile->addFixableError($error, $nextCloser, 'BreakIndent'); + if ($fix === true) { + if ($diff > 0) { + $phpcsFile->fixer->addContentBefore($nextCloser, str_repeat(' ', $diff)); + } else { + $phpcsFile->fixer->substrToken(($nextCloser - 1), 0, $diff); + } + } + } + }//end if + }//end if + } else { + $error = strtoupper($type).' statements must be defined using a colon'; + $phpcsFile->addError($error, $nextCase, 'WrongOpener'.$type); + }//end if + + // We only want cases from here on in. + if ($type !== 'case') { + continue; + } + + $nextCode = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), $nextCloser, true); + + if ($tokens[$nextCode]['code'] !== T_CASE && $tokens[$nextCode]['code'] !== T_DEFAULT) { + // This case statement has content. If the next case or default comes + // before the closer, it means we don't have an obvious terminating + // statement and need to make some more effort to find one. If we + // don't, we do need a comment. + $nextCode = $this->findNextCase($phpcsFile, ($opener + 1), $nextCloser); + if ($nextCode !== false) { + $prevCode = $phpcsFile->findPrevious(T_WHITESPACE, ($nextCode - 1), $nextCase, true); + if (isset(Tokens::$commentTokens[$tokens[$prevCode]['code']]) === false + && $this->findNestedTerminator($phpcsFile, ($opener + 1), $nextCode) === false + ) { + $error = 'There must be a comment when fall-through is intentional in a non-empty case body'; + $phpcsFile->addError($error, $nextCase, 'TerminatingComment'); + } + } + } + }//end while + + }//end process() + + + /** + * Find the next CASE or DEFAULT statement from a point in the file. + * + * Note that nested switches are ignored. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position to start looking at. + * @param int $end The position to stop looking at. + * + * @return int|false + */ + private function findNextCase($phpcsFile, $stackPtr, $end) + { + $tokens = $phpcsFile->getTokens(); + while (($stackPtr = $phpcsFile->findNext([T_CASE, T_DEFAULT, T_SWITCH], $stackPtr, $end)) !== false) { + // Skip nested SWITCH statements; they are handled on their own. + if ($tokens[$stackPtr]['code'] === T_SWITCH) { + $stackPtr = $tokens[$stackPtr]['scope_closer']; + continue; + } + + break; + } + + return $stackPtr; + + }//end findNextCase() + + + /** + * Returns the position of the nested terminating statement. + * + * Returns false if no terminating statement was found. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position to start looking at. + * @param int $end The position to stop looking at. + * + * @return int|bool + */ + private function findNestedTerminator($phpcsFile, $stackPtr, $end) + { + $tokens = $phpcsFile->getTokens(); + + $lastToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($end - 1), $stackPtr, true); + if ($lastToken === false) { + return false; + } + + if ($tokens[$lastToken]['code'] === T_CLOSE_CURLY_BRACKET) { + // We found a closing curly bracket and want to check if its block + // belongs to a SWITCH, IF, ELSEIF or ELSE, TRY, CATCH OR FINALLY clause. + // If yes, we continue searching for a terminating statement within that + // block. Note that we have to make sure that every block of + // the entire if/else/switch statement has a terminating statement. + // For a try/catch/finally statement, either the finally block has + // to have a terminating statement or every try/catch block has to have one. + $currentCloser = $lastToken; + $hasElseBlock = false; + $hasCatchWithoutTerminator = false; + do { + $scopeOpener = $tokens[$currentCloser]['scope_opener']; + $scopeCloser = $tokens[$currentCloser]['scope_closer']; + + $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($scopeOpener - 1), $stackPtr, true); + if ($prevToken === false) { + return false; + } + + // SWITCH, IF, ELSEIF, CATCH clauses possess a condition we have to account for. + if ($tokens[$prevToken]['code'] === T_CLOSE_PARENTHESIS) { + $prevToken = $tokens[$prevToken]['parenthesis_owner']; + } + + if ($tokens[$prevToken]['code'] === T_IF) { + // If we have not encountered an ELSE clause by now, we cannot + // be sure that the whole statement terminates in every case. + if ($hasElseBlock === false) { + return false; + } + + return $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser); + } else if ($tokens[$prevToken]['code'] === T_ELSEIF + || $tokens[$prevToken]['code'] === T_ELSE + ) { + // If we find a terminating statement within this block, + // we continue with the previous ELSEIF or IF clause. + $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser); + if ($hasTerminator === false) { + return false; + } + + $currentCloser = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prevToken - 1), $stackPtr, true); + if ($tokens[$prevToken]['code'] === T_ELSE) { + $hasElseBlock = true; + } + } else if ($tokens[$prevToken]['code'] === T_FINALLY) { + // If we find a terminating statement within this block, + // the whole try/catch/finally statement is covered. + $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser); + if ($hasTerminator !== false) { + return $hasTerminator; + } + + // Otherwise, we continue with the previous TRY or CATCH clause. + $currentCloser = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prevToken - 1), $stackPtr, true); + } else if ($tokens[$prevToken]['code'] === T_TRY) { + // If we've seen CATCH blocks without terminator statement and + // have not seen a FINALLY *with* a terminator statement, we + // don't even need to bother checking the TRY. + if ($hasCatchWithoutTerminator === true) { + return false; + } + + return $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser); + } else if ($tokens[$prevToken]['code'] === T_CATCH) { + // Keep track of seen catch statements without terminating statement, + // but don't bow out yet as there may still be a FINALLY clause + // with a terminating statement before the CATCH. + $hasTerminator = $this->findNestedTerminator($phpcsFile, ($scopeOpener + 1), $scopeCloser); + if ($hasTerminator === false) { + $hasCatchWithoutTerminator = true; + } + + $currentCloser = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prevToken - 1), $stackPtr, true); + } else if ($tokens[$prevToken]['code'] === T_SWITCH) { + $hasDefaultBlock = false; + $endOfSwitch = $tokens[$prevToken]['scope_closer']; + $nextCase = $prevToken; + + // We look for a terminating statement within every blocks. + while (($nextCase = $this->findNextCase($phpcsFile, ($nextCase + 1), $endOfSwitch)) !== false) { + if ($tokens[$nextCase]['code'] === T_DEFAULT) { + $hasDefaultBlock = true; + } + + $opener = $tokens[$nextCase]['scope_opener']; + + $nextCode = $phpcsFile->findNext(Tokens::$emptyTokens, ($opener + 1), $endOfSwitch, true); + if ($tokens[$nextCode]['code'] === T_CASE || $tokens[$nextCode]['code'] === T_DEFAULT) { + // This case statement has no content, so skip it. + continue; + } + + $endOfCase = $this->findNextCase($phpcsFile, ($opener + 1), $endOfSwitch); + if ($endOfCase === false) { + $endOfCase = $endOfSwitch; + } + + $hasTerminator = $this->findNestedTerminator($phpcsFile, ($opener + 1), $endOfCase); + if ($hasTerminator === false) { + return false; + } + }//end while + + // If we have not encountered a DEFAULT block by now, we cannot + // be sure that the whole statement terminates in every case. + if ($hasDefaultBlock === false) { + return false; + } + + return $hasTerminator; + } else { + return false; + }//end if + } while ($currentCloser !== false && $tokens[$currentCloser]['code'] === T_CLOSE_CURLY_BRACKET); + + return true; + } else if ($tokens[$lastToken]['code'] === T_SEMICOLON) { + // We found the last statement of the CASE. Now we want to + // check whether it is a terminating one. + $terminators = [ + T_RETURN => T_RETURN, + T_BREAK => T_BREAK, + T_CONTINUE => T_CONTINUE, + T_THROW => T_THROW, + T_EXIT => T_EXIT, + ]; + + $terminator = $phpcsFile->findStartOfStatement(($lastToken - 1)); + if (isset($terminators[$tokens[$terminator]['code']]) === true) { + return $terminator; + } + }//end if + + return false; + + }//end findNestedTerminator() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/ClosingTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/ClosingTagSniff.php new file mode 100644 index 0000000..1cb6374 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/ClosingTagSniff.php @@ -0,0 +1,89 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClosingTagSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Make sure this file only contains PHP code. + for ($i = 0; $i < $phpcsFile->numTokens; $i++) { + if ($tokens[$i]['code'] === T_INLINE_HTML + && trim($tokens[$i]['content']) !== '' + ) { + return $phpcsFile->numTokens; + } + } + + // Find the last non-empty token. + for ($last = ($phpcsFile->numTokens - 1); $last > 0; $last--) { + if (trim($tokens[$last]['content']) !== '') { + break; + } + } + + if ($tokens[$last]['code'] === T_CLOSE_TAG) { + $error = 'A closing tag is not permitted at the end of a PHP file'; + $fix = $phpcsFile->addFixableError($error, $last, 'NotAllowed'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($last, $phpcsFile->eolChar); + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($last - 1), null, true); + if ($tokens[$prev]['code'] !== T_SEMICOLON + && $tokens[$prev]['code'] !== T_CLOSE_CURLY_BRACKET + && $tokens[$prev]['code'] !== T_OPEN_TAG + ) { + $phpcsFile->fixer->addContent($prev, ';'); + } + + $phpcsFile->fixer->endChangeset(); + } + + $phpcsFile->recordMetric($stackPtr, 'PHP closing tag at end of PHP-only file', 'yes'); + } else { + $phpcsFile->recordMetric($stackPtr, 'PHP closing tag at end of PHP-only file', 'no'); + }//end if + + // Ignore the rest of the file. + return $phpcsFile->numTokens; + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/EndFileNewlineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/EndFileNewlineSniff.php new file mode 100644 index 0000000..d5e3e06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/EndFileNewlineSniff.php @@ -0,0 +1,107 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class EndFileNewlineSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($phpcsFile->findNext(T_INLINE_HTML, ($stackPtr + 1)) !== false) { + return ($phpcsFile->numTokens + 1); + } + + // Skip to the end of the file. + $tokens = $phpcsFile->getTokens(); + $lastToken = ($phpcsFile->numTokens - 1); + + if ($tokens[$lastToken]['content'] === '') { + $lastToken--; + } + + // Hard-coding the expected \n in this sniff as it is PSR-2 specific and + // PSR-2 enforces the use of unix style newlines. + if (substr($tokens[$lastToken]['content'], -1) !== "\n") { + $error = 'Expected 1 newline at end of file; 0 found'; + $fix = $phpcsFile->addFixableError($error, $lastToken, 'NoneFound'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($lastToken); + } + + $phpcsFile->recordMetric($stackPtr, 'Number of newlines at EOF', '0'); + return ($phpcsFile->numTokens + 1); + } + + // Go looking for the last non-empty line. + $lastLine = $tokens[$lastToken]['line']; + if ($tokens[$lastToken]['code'] === T_WHITESPACE + || $tokens[$lastToken]['code'] === T_DOC_COMMENT_WHITESPACE + ) { + $lastCode = $phpcsFile->findPrevious([T_WHITESPACE, T_DOC_COMMENT_WHITESPACE], ($lastToken - 1), null, true); + } else { + $lastCode = $lastToken; + } + + $lastCodeLine = $tokens[$lastCode]['line']; + $blankLines = ($lastLine - $lastCodeLine + 1); + $phpcsFile->recordMetric($stackPtr, 'Number of newlines at EOF', $blankLines); + + if ($blankLines > 1) { + $error = 'Expected 1 blank line at end of file; %s found'; + $data = [$blankLines]; + $fix = $phpcsFile->addFixableError($error, $lastCode, 'TooMany', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($lastCode, rtrim($tokens[$lastCode]['content'])); + for ($i = ($lastCode + 1); $i < $lastToken; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken($lastToken, $phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } + + // Skip the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionCallSignatureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionCallSignatureSniff.php new file mode 100644 index 0000000..cee18ca --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionCallSignatureSniff.php @@ -0,0 +1,79 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionCallSignatureSniff as PEARFunctionCallSignatureSniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionCallSignatureSniff extends PEARFunctionCallSignatureSniff +{ + + /** + * If TRUE, multiple arguments can be defined per line in a multi-line call. + * + * @var boolean + */ + public $allowMultipleArguments = false; + + + /** + * Processes single-line calls. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return bool + */ + public function isMultiLineCall(File $phpcsFile, $stackPtr, $openBracket, $tokens) + { + // If the first argument is on a new line, this is a multi-line + // function call, even if there is only one argument. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + return true; + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + $end = $phpcsFile->findEndOfStatement(($openBracket + 1), [T_COLON]); + while ($tokens[$end]['code'] === T_COMMA) { + // If the next bit of code is not on the same line, this is a + // multi-line function call. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); + if ($next === false) { + return false; + } + + if ($tokens[$next]['line'] !== $tokens[$end]['line']) { + return true; + } + + $end = $phpcsFile->findEndOfStatement($next, [T_COLON]); + } + + // We've reached the last argument, so see if the next content + // (should be the close bracket) is also on the same line. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); + if ($next !== false && $tokens[$next]['line'] !== $tokens[$end]['line']) { + return true; + } + + return false; + + }//end isMultiLineCall() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionClosingBraceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionClosingBraceSniff.php new file mode 100644 index 0000000..c4f1a6f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionClosingBraceSniff.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FunctionClosingBraceSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + // Probably an interface method. + return; + } + + $closeBrace = $tokens[$stackPtr]['scope_closer']; + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBrace - 1), null, true); + $found = ($tokens[$closeBrace]['line'] - $tokens[$prevContent]['line'] - 1); + + if ($found < 0) { + // Brace isn't on a new line, so not handled by us. + return; + } + + if ($found === 0) { + // All is good. + return; + } + + $error = 'Function closing brace must go on the next line following the body; found %s blank lines before brace'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBeforeClose', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prevContent + 1); $i < $closeBrace; $i++) { + if ($tokens[$i]['line'] === $tokens[$prevContent]['line']) { + continue; + } + + // Don't remove any indentation before the brace. + if ($tokens[$i]['line'] === $tokens[$closeBrace]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/MethodDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/MethodDeclarationSniff.php new file mode 100644 index 0000000..6500d04 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/MethodDeclarationSniff.php @@ -0,0 +1,162 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Tokens; + +class MethodDeclarationSniff extends AbstractScopeSniff +{ + + + /** + * Constructs a Squiz_Sniffs_Scope_MethodScopeSniff. + */ + public function __construct() + { + parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION]); + + }//end __construct() + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * @param int $currScope The current scope opener token. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + + if ($methodName[0] === '_' && isset($methodName[1]) === true && $methodName[1] !== '_') { + $error = 'Method name "%s" should not be prefixed with an underscore to indicate visibility'; + $data = [$methodName]; + $phpcsFile->addWarning($error, $stackPtr, 'Underscore', $data); + } + + $visibility = 0; + $static = 0; + $abstract = 0; + $final = 0; + + $find = (Tokens::$methodPrefixes + Tokens::$emptyTokens); + $prev = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + + $prefix = $stackPtr; + while (($prefix = $phpcsFile->findPrevious(Tokens::$methodPrefixes, ($prefix - 1), $prev)) !== false) { + switch ($tokens[$prefix]['code']) { + case T_STATIC: + $static = $prefix; + break; + case T_ABSTRACT: + $abstract = $prefix; + break; + case T_FINAL: + $final = $prefix; + break; + default: + $visibility = $prefix; + break; + } + } + + $fixes = []; + + if ($visibility !== 0 && $final > $visibility) { + $error = 'The final declaration must precede the visibility declaration'; + $fix = $phpcsFile->addFixableError($error, $final, 'FinalAfterVisibility'); + if ($fix === true) { + $fixes[$final] = ''; + $fixes[($final + 1)] = ''; + if (isset($fixes[$visibility]) === true) { + $fixes[$visibility] = 'final '.$fixes[$visibility]; + } else { + $fixes[$visibility] = 'final '.$tokens[$visibility]['content']; + } + } + } + + if ($visibility !== 0 && $abstract > $visibility) { + $error = 'The abstract declaration must precede the visibility declaration'; + $fix = $phpcsFile->addFixableError($error, $abstract, 'AbstractAfterVisibility'); + if ($fix === true) { + $fixes[$abstract] = ''; + $fixes[($abstract + 1)] = ''; + if (isset($fixes[$visibility]) === true) { + $fixes[$visibility] = 'abstract '.$fixes[$visibility]; + } else { + $fixes[$visibility] = 'abstract '.$tokens[$visibility]['content']; + } + } + } + + if ($static !== 0 && $static < $visibility) { + $error = 'The static declaration must come after the visibility declaration'; + $fix = $phpcsFile->addFixableError($error, $static, 'StaticBeforeVisibility'); + if ($fix === true) { + $fixes[$static] = ''; + $fixes[($static + 1)] = ''; + if (isset($fixes[$visibility]) === true) { + $fixes[$visibility] .= ' static'; + } else { + $fixes[$visibility] = $tokens[$visibility]['content'].' static'; + } + } + } + + // Batch all the fixes together to reduce the possibility of conflicts. + if (empty($fixes) === false) { + $phpcsFile->fixer->beginChangeset(); + foreach ($fixes as $stackPtr => $content) { + $phpcsFile->fixer->replaceToken($stackPtr, $content); + } + + $phpcsFile->fixer->endChangeset(); + } + + }//end processTokenWithinScope() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/NamespaceDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/NamespaceDeclarationSniff.php new file mode 100644 index 0000000..7b1dad1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/NamespaceDeclarationSniff.php @@ -0,0 +1,100 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class NamespaceDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_NAMESPACE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($tokens[$nextNonEmpty]['code'] === T_NS_SEPARATOR) { + // Namespace keyword as operator. Not a declaration. + return; + } + + $end = $phpcsFile->findEndOfStatement($stackPtr); + for ($i = ($end + 1); $i < ($phpcsFile->numTokens - 1); $i++) { + if ($tokens[$i]['line'] === $tokens[$end]['line']) { + continue; + } + + break; + } + + // The $i var now points to the first token on the line after the + // namespace declaration, which must be a blank line. + $next = $phpcsFile->findNext(T_WHITESPACE, $i, $phpcsFile->numTokens, true); + if ($next === false) { + return; + } + + $diff = ($tokens[$next]['line'] - $tokens[$i]['line']); + if ($diff === 1) { + return; + } + + if ($diff < 0) { + $diff = 0; + } + + $error = 'There must be one blank line after the namespace declaration'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'BlankLineAfter'); + + if ($fix === true) { + if ($diff === 0) { + $phpcsFile->fixer->addNewlineBefore($i); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($x = $i; $x < $next; $x++) { + if ($tokens[$x]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($x, ''); + } + + $phpcsFile->fixer->addNewline($i); + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/UseDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/UseDeclarationSniff.php new file mode 100644 index 0000000..1882fd9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/UseDeclarationSniff.php @@ -0,0 +1,297 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class UseDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_USE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($this->shouldIgnoreUse($phpcsFile, $stackPtr) === true) { + return; + } + + $tokens = $phpcsFile->getTokens(); + + // One space after the use keyword. + if ($tokens[($stackPtr + 1)]['content'] !== ' ') { + $error = 'There must be a single space after the USE keyword'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterUse'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + + // Only one USE declaration allowed per statement. + $next = $phpcsFile->findNext([T_COMMA, T_SEMICOLON, T_OPEN_USE_GROUP, T_CLOSE_TAG], ($stackPtr + 1)); + if ($next !== false + && $tokens[$next]['code'] !== T_SEMICOLON + && $tokens[$next]['code'] !== T_CLOSE_TAG + ) { + $error = 'There must be one USE keyword per declaration'; + + if ($tokens[$next]['code'] === T_COMMA) { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'MultipleDeclarations'); + if ($fix === true) { + switch ($tokens[($stackPtr + 2)]['content']) { + case 'const': + $baseUse = 'use const'; + break; + case 'function': + $baseUse = 'use function'; + break; + default: + $baseUse = 'use'; + } + + if ($tokens[($next + 1)]['code'] !== T_WHITESPACE) { + $baseUse .= ' '; + } + + $phpcsFile->fixer->replaceToken($next, ';'.$phpcsFile->eolChar.$baseUse); + } + } else { + $closingCurly = $phpcsFile->findNext(T_CLOSE_USE_GROUP, ($next + 1)); + if ($closingCurly === false) { + // Parse error or live coding. Not auto-fixable. + $phpcsFile->addError($error, $stackPtr, 'MultipleDeclarations'); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'MultipleDeclarations'); + if ($fix === true) { + $baseUse = rtrim($phpcsFile->getTokensAsString($stackPtr, ($next - $stackPtr))); + $lastNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($closingCurly - 1), null, true); + + $phpcsFile->fixer->beginChangeset(); + + // Remove base use statement. + for ($i = $stackPtr; $i <= $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + if (preg_match('`^[\r\n]+$`', $tokens[($next + 1)]['content']) === 1) { + $phpcsFile->fixer->replaceToken(($next + 1), ''); + } + + // Convert grouped use statements into full use statements. + do { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), $closingCurly, true); + if ($next === false) { + // Group use statement with trailing comma after last item. + break; + } + + $nonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($next - 1), null, true); + for ($i = ($nonWhitespace + 1); $i < $next; $i++) { + if (preg_match('`^[\r\n]+$`', $tokens[$i]['content']) === 1) { + // Preserve new lines. + continue; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + if ($tokens[$next]['content'] === 'const' || $tokens[$next]['content'] === 'function') { + $phpcsFile->fixer->addContentBefore($next, 'use '); + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), $closingCurly, true); + $phpcsFile->fixer->addContentBefore($next, str_replace('use ', '', $baseUse)); + } else { + $phpcsFile->fixer->addContentBefore($next, $baseUse); + } + + $next = $phpcsFile->findNext(T_COMMA, ($next + 1), $closingCurly); + if ($next !== false) { + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), $closingCurly, true); + if ($nextNonEmpty !== false && $tokens[$nextNonEmpty]['line'] === $tokens[$next]['line']) { + $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($nextNonEmpty - 1), $next, true); + if ($prevNonWhitespace === $next) { + $phpcsFile->fixer->replaceToken($next, ';'.$phpcsFile->eolChar); + } else { + $phpcsFile->fixer->replaceToken($next, ';'); + $phpcsFile->fixer->addNewline($prevNonWhitespace); + } + } else { + // Last item with trailing comma or next item already on new line. + $phpcsFile->fixer->replaceToken($next, ';'); + } + } else { + // Last item without trailing comma. + $phpcsFile->fixer->addContent($lastNonWhitespace, ';'); + } + } while ($next !== false); + + // Remove closing curly,semi-colon and any whitespace between last child and closing curly. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($closingCurly + 1), null, true); + if ($next === false || $tokens[$next]['code'] !== T_SEMICOLON) { + // Parse error, forgotten semi-colon. + $next = $closingCurly; + } + + for ($i = ($lastNonWhitespace + 1); $i <= $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + }//end if + }//end if + + // Make sure this USE comes after the first namespace declaration. + $prev = $phpcsFile->findPrevious(T_NAMESPACE, ($stackPtr - 1)); + if ($prev === false) { + $next = $phpcsFile->findNext(T_NAMESPACE, ($stackPtr + 1)); + if ($next !== false) { + $error = 'USE declarations must go after the namespace declaration'; + $phpcsFile->addError($error, $stackPtr, 'UseBeforeNamespace'); + } + } + + // Only interested in the last USE statement from here onwards. + $nextUse = $phpcsFile->findNext(T_USE, ($stackPtr + 1)); + while ($this->shouldIgnoreUse($phpcsFile, $nextUse) === true) { + $nextUse = $phpcsFile->findNext(T_USE, ($nextUse + 1)); + if ($nextUse === false) { + break; + } + } + + if ($nextUse !== false) { + return; + } + + $end = $phpcsFile->findNext([T_SEMICOLON, T_CLOSE_USE_GROUP, T_CLOSE_TAG], ($stackPtr + 1)); + if ($end === false) { + return; + } + + if ($tokens[$end]['code'] === T_CLOSE_USE_GROUP) { + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true); + if ($tokens[$nextNonEmpty]['code'] === T_SEMICOLON) { + $end = $nextNonEmpty; + } + } + + // Find either the start of the next line or the beginning of the next statement, + // whichever comes first. + for ($end = ++$end; $end < $phpcsFile->numTokens; $end++) { + if (isset(Tokens::$emptyTokens[$tokens[$end]['code']]) === false) { + break; + } + + if ($tokens[$end]['column'] === 1) { + // Reached the next line. + break; + } + } + + --$end; + + if (($tokens[$end]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$end]['code']]) === true) + && substr($tokens[$end]['content'], 0, 2) === '/*' + && substr($tokens[$end]['content'], -2) !== '*/' + ) { + // Multi-line block comments are not allowed as trailing comment after a use statement. + --$end; + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($end + 1), null, true); + + if ($next === false || $tokens[$next]['code'] === T_CLOSE_TAG) { + return; + } + + $diff = ($tokens[$next]['line'] - $tokens[$end]['line'] - 1); + if ($diff !== 1) { + if ($diff < 0) { + $diff = 0; + } + + $error = 'There must be one blank line after the last USE statement; %s found;'; + $data = [$diff]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterLastUse', $data); + if ($fix === true) { + if ($diff === 0) { + $phpcsFile->fixer->addNewline($end); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($end + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addNewline($end); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end process() + + + /** + * Check if this use statement is part of the namespace block. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return bool + */ + private function shouldIgnoreUse($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore USE keywords inside closures and during live coding. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($next === false || $tokens[$next]['code'] === T_OPEN_PARENTHESIS) { + return true; + } + + // Ignore USE keywords for traits. + if ($phpcsFile->hasCondition($stackPtr, [T_CLASS, T_TRAIT, T_ENUM]) === true) { + return true; + } + + return false; + + }//end shouldIgnoreUse() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc new file mode 100644 index 0000000..f241a1a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc @@ -0,0 +1,259 @@ +anonymous = new class extends ArrayObject + { + public function __construct() + { + parent::__construct(['a' => 1, 'b' => 2]); + } + }; + } +} + +class A extends B + implements C +{ +} + +class C2 +{ + +} // phpcs:ignore Standard.Category.Sniff + +interface I1 extends + Foo +{ +} + +interface I2 extends + Bar +{ +} + +interface I3 extends + Foo, + Bar +{ +} + +class C1 extends + Foo +{ +} + +class C2 extends + Bar +{ +} + +class C3 extends Foo implements + Bar +{ +} + +class C4 extends Foo implements + Bar +{ +} + +class C5 extends Foo implements + Bar, + Baz +{ +} + +class C6 extends \Foo\Bar implements + \Baz\Bar +{ +} + +interface I4 extends + \Baz + \Bar +{ +} + +interface I5 extends /* comment */ + \Foo\Bar +{ +} + +interface I6 extends // comment + \Foo\Bar +{ +} + +class C7 extends // comment + \Foo\Bar implements \Baz\Bar +{ +} + +class +C8 +{ +} + +foo(new class { +}); + +readonly +class Test +{ +} + +readonly class Test +{ +} + +if (!class_exists('IndentedDeclaration')) { + class IndentedDeclaration + { + function foo() {} + + + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..bb72318 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc.fixed @@ -0,0 +1,249 @@ +anonymous = new class extends ArrayObject + { + public function __construct() + { + parent::__construct(['a' => 1, 'b' => 2]); + } + }; + } +} + +class A extends B implements C +{ +} + +class C2 +{ + +} // phpcs:ignore Standard.Category.Sniff + +interface I1 extends + Foo +{ +} + +interface I2 extends + Bar +{ +} + +interface I3 extends + Foo, + Bar +{ +} + +class C1 extends Foo +{ +} + +class C2 extends Bar +{ +} + +class C3 extends Foo implements + Bar +{ +} + +class C4 extends Foo implements + Bar +{ +} + +class C5 extends Foo implements + Bar, + Baz +{ +} + +class C6 extends \Foo\Bar implements + \Baz\Bar +{ +} + +interface I4 extends + \Baz\Bar +{ +} + +interface I5 extends /* comment */ + \Foo\Bar +{ +} + +interface I6 extends // comment + \Foo\Bar +{ +} + +class C7 extends \Foo\Bar implements \Baz\Bar // comment +{ +} + +class C8 +{ +} + +foo(new class { +}); + +readonly class Test +{ +} + +readonly class Test +{ +} + +if (!class_exists('IndentedDeclaration')) { + class IndentedDeclaration + { + function foo() {} + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.php new file mode 100644 index 0000000..df574cb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.php @@ -0,0 +1,94 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff + */ +class ClassDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 7 => 3, + 12 => 1, + 13 => 1, + 17 => 1, + 19 => 2, + 20 => 1, + 21 => 1, + 22 => 1, + 25 => 1, + 27 => 2, + 34 => 1, + 35 => 2, + 44 => 1, + 45 => 1, + 63 => 1, + 95 => 1, + 116 => 1, + 118 => 1, + 119 => 1, + 124 => 1, + 130 => 2, + 131 => 1, + 158 => 1, + 168 => 1, + 178 => 1, + 179 => 1, + 184 => 1, + 189 => 1, + 194 => 1, + 204 => 1, + 205 => 1, + 210 => 1, + 215 => 2, + 216 => 1, + 231 => 2, + 235 => 1, + 244 => 1, + 248 => 1, + 258 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/PropertyDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/PropertyDeclarationUnitTest.inc new file mode 100644 index 0000000..3e086c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Classes/PropertyDeclarationUnitTest.inc @@ -0,0 +1,87 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the PropertyDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\PropertyDeclarationSniff + */ +class PropertyDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 9 => 2, + 10 => 1, + 11 => 1, + 17 => 1, + 18 => 1, + 23 => 1, + 38 => 1, + 41 => 1, + 42 => 1, + 50 => 2, + 51 => 1, + 55 => 1, + 56 => 1, + 61 => 1, + 62 => 1, + 68 => 1, + 69 => 1, + 71 => 1, + 72 => 1, + 76 => 1, + 80 => 1, + 82 => 1, + 84 => 1, + 86 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 13 => 1, + 14 => 1, + 15 => 1, + 53 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc new file mode 100644 index 0000000..542ab3c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc @@ -0,0 +1,81 @@ + $that) {} +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 0 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 0 + +$binary = b"binary string"; + +if ($expr1 + && $expr2 ) { +} + +if ($expr1 + && $expr2 /* comment */ ) { +} + +if ($expr1 + && $expr2 + /* comment */ ) { +} + +$r = match ($x) {}; +$r = match ( $x ) {}; + +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 1 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 1 +$r = match ($x) {}; +$r = match ( $x ) {}; +$r = match ( $x ) {}; +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 0 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 0 diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..a29534b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.inc.fixed @@ -0,0 +1,80 @@ + $that ) {} +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 0 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 0 + +$binary = b"binary string"; + +if ($expr1 + && $expr2) { +} + +if ($expr1 + && $expr2 /* comment */) { +} + +if ($expr1 + && $expr2 + /* comment */) { +} + +$r = match ($x) {}; +$r = match ($x) {}; + +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 1 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 1 +$r = match ( $x ) {}; +$r = match ( $x ) {}; +$r = match ( $x ) {}; +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesAfterOpen 0 +// phpcs:set PSR2.ControlStructures.ControlStructureSpacing requiredSpacesBeforeClose 0 diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.php new file mode 100644 index 0000000..0ddd9a4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ControlStructureSpacingUnitTest.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ControlStructureSpacingSniff + */ +class ControlStructureSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 14 => 2, + 26 => 2, + 27 => 2, + 31 => 1, + 51 => 2, + 53 => 2, + 60 => 1, + 64 => 1, + 69 => 1, + 73 => 2, + 77 => 2, + 79 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc new file mode 100644 index 0000000..778659c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..4a7bfdc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc.fixed @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.php new file mode 100644 index 0000000..d646689 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/ElseIfDeclarationUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ElseIfDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ElseIfDeclarationSniff + */ +class ElseIfDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 4 => 1, + 12 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc new file mode 100644 index 0000000..2ca60a9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc @@ -0,0 +1,598 @@ + 0) { + return 0; + } else { + return 1; + } + case 2: + return 2; +} + +// ERROR: No else clause +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } elseif ($bar < 0) { + return 1; + } + case 2: + return 2; +} + +// OK: No fall-through present +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } elseif ($bar < 0) { + return 1; + } +} + +// ERROR: No else clause (nested) +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } else { + if ($foo > $bar) { + continue; + } + } + case 2: + return 2; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } else { + if ($foo > $bar) { + continue; + } else { + break; + } + } + case 2: + return 2; +} + +// ERROR: Non-termination IF clause +switch ($foo) { + case 1: + if ($bar > 0) { + $offset = 0; + } else { + break; + } + case 2: + return 2; +} + +// ERROR: Non-termination IF clause (nested) +switch ($foo) { + case 1: + if ($bar > 0) { + continue; + } else { + if ($foo > $bar) { + $offset = 0; + } else { + break; + } + } + case 2: + return 2; +} + +switch ($sContext) +{ + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +$foo = $foo ? + function () { + switch ($a) { + case 'a': + break; + } + } : + null; + +switch ($foo) { +case Foo::INTERFACE: + echo '1'; + return self::INTERFACE; +case Foo::TRAIT: +case Foo::ARRAY: + echo '1'; + return self::VALUE; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return 1; + default: + return 3; + } + case 2: + return 2; +} + +// KO: Not every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return; + } + case 2: + return 2; +} + +// KO: Not every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return; + default: + $a = 1; + } + case 2: + return 2; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return 1; + default: + throw new \Exception(); + } + case 2: + return 2; +} + +switch ($foo) { + case 1: + // phpcs:ignore + case 2: + return 1; + case 3: + return 2; +} + +// Issue 3352. +switch ( $test ) { + case 2: // comment followed by empty line + + break; + + case 3: /* phpcs:ignore Stnd.Cat.SniffName -- Verify correct handling of ignore comments. */ + + + + break; + + case 4: /** inline docblock */ + + + + break; + + case 5: /* checking how it handles */ /* two trailing comments */ + + break; + + case 6: + // Comment as first content of the body. + + break; + + case 7: + /* phpcs:ignore Stnd.Cat.SniffName -- Verify correct handling of ignore comments at start of body. */ + + break; + + case 8: + /** inline docblock */ + + break; +} + +// Handle comments correctly. +switch ($foo) { + case 1: + if ($bar > 0) { + doSomething(); + } + // Comment + else { + return 1; + } + case 2: + return 2; +} + +switch ($foo) { + case 1: + if ($bar > 0) /*comment*/ { + return doSomething(); + } + else { + return 1; + } + case 2: + return 2; +} + +// Issue #3297. +// Okay - finally will always be executed, so all branches are covered by the `return` in finally. +switch ( $a ) { + case 1: + try { + doSomething(); + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + doSomething(); + } finally { + return true; + } + default: + $other = $code; + break; +} + +// Okay - all - non-finally - branches have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) /*comment*/ { + return true; + } + // Comment + catch (AnotherException $e) { + return true; + } finally { + doSomething(); + } + default: + $other = $code; + break; +} + +// Okay - finally will always be executed, so all branches are covered by the `return` in finally. +// Non-standard structure order. +switch ( $a ) { + case 1: + try { + doSomething(); + } catch (Exception $e) { + doSomething(); + } finally { + return true; + } catch (AnotherException $e) { + doSomething(); + } + default: + $other = $code; + break; +} + +// Okay - all - non-finally - branches have a terminating statement. +// Non-standard structure order. +switch ( $a ) { + case 1: + try { + return false; + } finally { + doSomething(); + } catch (MyException $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// All okay, no finally. Any exception still uncaught will terminate the case anyhow, so we're good. +switch ( $a ) { + case 1: + try { + return false; + } catch (MyException $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// All okay, no catch +switch ( $a ) { + case 1: + try { + return true; + } finally { + doSomething(); + } + case 2: + $other = $code; + break; +} + +// All okay, try-catch nested in if. +switch ( $a ) { + case 1: + if ($a) { + try { + return true; // Comment. + } catch (MyException $e) { + throw new Exception($e->getMessage()); + } + } else { + return true; + } + case 2: + $other = $code; + break; +} + +// Missing fall-through comment. +switch ( $a ) { + case 1: + try { + doSomething(); + } finally { + doSomething(); + } + case 2: + $other = $code; + break; +} + +// Missing fall-through comment. One of the catches does not have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + return true; + } finally { + doSomething(); + } + default: + $other = $code; + break; +} + +// Missing fall-through comment. Try does not have a terminating statement. +switch ( $a ) { + case 1: + try { + doSomething(); + } finally { + doSomething(); + } catch (Exception $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// Missing fall-through comment. One of the catches does not have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// Issue 3550 - comment after terminating statement. +switch (rand()) { + case 1: + if (rand() === 1) { + break; + } else { + break; // comment + } + default: + break; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..bbc8b7c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.inc.fixed @@ -0,0 +1,593 @@ + 0) { + return 0; + } else { + return 1; + } + case 2: + return 2; +} + +// ERROR: No else clause +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } elseif ($bar < 0) { + return 1; + } + case 2: + return 2; +} + +// OK: No fall-through present +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } elseif ($bar < 0) { + return 1; + } +} + +// ERROR: No else clause (nested) +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } else { + if ($foo > $bar) { + continue; + } + } + case 2: + return 2; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + if ($bar > 0) { + return 0; + } else { + if ($foo > $bar) { + continue; + } else { + break; + } + } + case 2: + return 2; +} + +// ERROR: Non-termination IF clause +switch ($foo) { + case 1: + if ($bar > 0) { + $offset = 0; + } else { + break; + } + case 2: + return 2; +} + +// ERROR: Non-termination IF clause (nested) +switch ($foo) { + case 1: + if ($bar > 0) { + continue; + } else { + if ($foo > $bar) { + $offset = 0; + } else { + break; + } + } + case 2: + return 2; +} + +switch ($sContext) +{ + case 'SOMETHING': + case 'CONSTANT': + do_something(); + break; + case 'GLOBAL': + case 'GLOBAL1': + do_something(); + // Fall through + default: + { + do_something(); + } +} + +$foo = $foo ? + function () { + switch ($a) { + case 'a': + break; + } + } : + null; + +switch ($foo) { +case Foo::INTERFACE: + echo '1'; + return self::INTERFACE; +case Foo::TRAIT: +case Foo::ARRAY: + echo '1'; + return self::VALUE; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return 1; + default: + return 3; + } + case 2: + return 2; +} + +// KO: Not every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return; + } + case 2: + return 2; +} + +// KO: Not every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return; + default: + $a = 1; + } + case 2: + return 2; +} + +// OK: Every clause terminates +switch ($foo) { + case 1: + switch ($bar) { + case 1: + return 1; + default: + throw new \Exception(); + } + case 2: + return 2; +} + +switch ($foo) { + case 1: + // phpcs:ignore + case 2: + return 1; + case 3: + return 2; +} + +// Issue 3352. +switch ( $test ) { + case 2: // comment followed by empty line + break; + + case 3: /* phpcs:ignore Stnd.Cat.SniffName -- Verify correct handling of ignore comments. */ + break; + + case 4: /** inline docblock */ + break; + + case 5: /* checking how it handles */ /* two trailing comments */ + break; + + case 6: + // Comment as first content of the body. + + break; + + case 7: + /* phpcs:ignore Stnd.Cat.SniffName -- Verify correct handling of ignore comments at start of body. */ + + break; + + case 8: + /** inline docblock */ + + break; +} + +// Handle comments correctly. +switch ($foo) { + case 1: + if ($bar > 0) { + doSomething(); + } + // Comment + else { + return 1; + } + case 2: + return 2; +} + +switch ($foo) { + case 1: + if ($bar > 0) /*comment*/ { + return doSomething(); + } + else { + return 1; + } + case 2: + return 2; +} + +// Issue #3297. +// Okay - finally will always be executed, so all branches are covered by the `return` in finally. +switch ( $a ) { + case 1: + try { + doSomething(); + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + doSomething(); + } finally { + return true; + } + default: + $other = $code; + break; +} + +// Okay - all - non-finally - branches have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) /*comment*/ { + return true; + } + // Comment + catch (AnotherException $e) { + return true; + } finally { + doSomething(); + } + default: + $other = $code; + break; +} + +// Okay - finally will always be executed, so all branches are covered by the `return` in finally. +// Non-standard structure order. +switch ( $a ) { + case 1: + try { + doSomething(); + } catch (Exception $e) { + doSomething(); + } finally { + return true; + } catch (AnotherException $e) { + doSomething(); + } + default: + $other = $code; + break; +} + +// Okay - all - non-finally - branches have a terminating statement. +// Non-standard structure order. +switch ( $a ) { + case 1: + try { + return false; + } finally { + doSomething(); + } catch (MyException $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// All okay, no finally. Any exception still uncaught will terminate the case anyhow, so we're good. +switch ( $a ) { + case 1: + try { + return false; + } catch (MyException $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// All okay, no catch +switch ( $a ) { + case 1: + try { + return true; + } finally { + doSomething(); + } + case 2: + $other = $code; + break; +} + +// All okay, try-catch nested in if. +switch ( $a ) { + case 1: + if ($a) { + try { + return true; // Comment. + } catch (MyException $e) { + throw new Exception($e->getMessage()); + } + } else { + return true; + } + case 2: + $other = $code; + break; +} + +// Missing fall-through comment. +switch ( $a ) { + case 1: + try { + doSomething(); + } finally { + doSomething(); + } + case 2: + $other = $code; + break; +} + +// Missing fall-through comment. One of the catches does not have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + return true; + } finally { + doSomething(); + } + default: + $other = $code; + break; +} + +// Missing fall-through comment. Try does not have a terminating statement. +switch ( $a ) { + case 1: + try { + doSomething(); + } finally { + doSomething(); + } catch (Exception $e) { + return true; + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// Missing fall-through comment. One of the catches does not have a terminating statement. +switch ( $a ) { + case 1: + try { + return false; + } catch (Exception $e) { + doSomething(); + } catch (AnotherException $e) { + return true; + } + default: + $other = $code; + break; +} + +// Issue 3550 - comment after terminating statement. +switch (rand()) { + case 1: + if (rand() === 1) { + break; + } else { + break; // comment + } + default: + break; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.php new file mode 100644 index 0000000..cd4c19f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/ControlStructures/SwitchDeclarationUnitTest.php @@ -0,0 +1,86 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SwitchDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\SwitchDeclarationSniff + */ +class SwitchDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 10 => 1, + 11 => 1, + 14 => 1, + 16 => 1, + 20 => 1, + 23 => 1, + 29 => 1, + 33 => 1, + 37 => 2, + 108 => 2, + 109 => 1, + 111 => 1, + 113 => 2, + 114 => 1, + 128 => 1, + 141 => 1, + 172 => 1, + 194 => 1, + 224 => 1, + 236 => 1, + 260 => 1, + 300 => 1, + 311 => 1, + 346 => 1, + 350 => 1, + 356 => 1, + 362 => 1, + 384 => 1, + 528 => 1, + 541 => 1, + 558 => 1, + 575 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc new file mode 100644 index 0000000..738e70e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc @@ -0,0 +1,12 @@ + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc.fixed new file mode 100644 index 0000000..f70b9eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.1.inc.fixed @@ -0,0 +1,12 @@ + + +
    + +
    \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.3.inc new file mode 100644 index 0000000..d6a8617 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.3.inc @@ -0,0 +1,7 @@ + + +A: +B: +C: \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc new file mode 100644 index 0000000..dd103cd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc @@ -0,0 +1 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc.fixed new file mode 100644 index 0000000..1058f1f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.4.inc.fixed @@ -0,0 +1 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.5.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.5.inc.fixed new file mode 100644 index 0000000..93d55fb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.5.inc.fixed @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.6.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.6.inc.fixed new file mode 100644 index 0000000..534574d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.6.inc.fixed @@ -0,0 +1,5 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.7.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.7.inc.fixed new file mode 100644 index 0000000..68e7d8c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/ClosingTagUnitTest.7.inc.fixed @@ -0,0 +1,5 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClosingTag sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Files\ClosingTagSniff + */ +class ClosingTagUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ClosingTagUnitTest.1.inc': + return [11 => 1]; + + case 'ClosingTagUnitTest.4.inc': + case 'ClosingTagUnitTest.5.inc': + return [1 => 1]; + + case 'ClosingTagUnitTest.6.inc': + case 'ClosingTagUnitTest.7.inc': + return [5 => 1]; + + default: + return []; + } + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.1.inc new file mode 100644 index 0000000..ca2a749 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.1.inc @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.12.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.12.inc.fixed new file mode 100644 index 0000000..d3c19fe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.12.inc.fixed @@ -0,0 +1 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.13.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.13.inc new file mode 100644 index 0000000..fa2f476 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.13.inc @@ -0,0 +1,5 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.2.inc new file mode 100644 index 0000000..1254e4a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.2.inc @@ -0,0 +1,2 @@ + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.5.inc new file mode 100644 index 0000000..c3a59b6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Files/EndFileNewlineUnitTest.5.inc @@ -0,0 +1,6 @@ + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EndFileNewline sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Files\EndFileNewlineSniff + */ +class EndFileNewlineUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'EndFileNewlineUnitTest.1.inc': + case 'EndFileNewlineUnitTest.3.inc': + case 'EndFileNewlineUnitTest.6.inc': + case 'EndFileNewlineUnitTest.7.inc': + case 'EndFileNewlineUnitTest.9.inc': + case 'EndFileNewlineUnitTest.10.inc': + return [2 => 1]; + case 'EndFileNewlineUnitTest.11.inc': + case 'EndFileNewlineUnitTest.12.inc': + case 'EndFileNewlineUnitTest.13.inc': + return [1 => 1]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc new file mode 100644 index 0000000..1ca477d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc @@ -0,0 +1,267 @@ +get('/hello/{name}', function ($name) use ($app) { + return 'Hello '.$app->escape($name); +}, array( + '1', + '2', + '3', +)); + +// error +somefunction2($foo, $bar, [ + // ... + ], +$baz); + +// ok +somefunction3(// ... + $foo, + $bar, + [ + // ... + ], + $baz +); + +// ok +somefunction4(' + this should not + give an error + because it\'s actually + one line call + with multi-line string +'); + +// ok +somefunction5("hey, +multi-line string with some +extra args", $foo, 12); + +// error +somefunction6(' + but args in a new line + are not ok… + ', + $foo +); + +$this->setFoo(true + ? 1 + : 2, false, array( + 'value', + 'more')); + +$this->setFoo('some' + . 'long' + . 'text', 'string'); + +foo(bar(), $a); +foo();bar(); + +foo( + true +); + +myFunction(<< function ($x) { + return true; + }, + 'baz' => false + ) +); +$qux = array_filter( + $quux, function ($x) { + return $x; + } +); + +$this->listeners[] = $events->getSharedManager()->attach( + 'Zend\Mvc\Application', MvcEvent::EVENT_DISPATCH, [$this, 'selectLayout'], 100 +); + +// phpcs:set PSR2.Methods.FunctionCallSignature requiredSpacesBeforeClose 1 +foo('Testing + multiline text' + ); + +foo('Testing + multiline text: ' // . $text + ); + +foo('Testing + multiline text: ' /* . $text */ + ); + +foo('Testing + multiline text: ' /* . $text */ + // . $other_text + ); + +foo('Testing + multiline text: ' /* + . $text +// . $text2 + */ + ); +// phpcs:set PSR2.Methods.FunctionCallSignature requiredSpacesBeforeClose 0 + +foo('Testing + multiline text' +); + +foo('Testing + multiline text' + ); + +foo('Testing + multiline text' // hello +); + +foo('Testing + multiline text' /* hello */ +); + +foo('Testing + multiline text' + // hello +); + +foo('Testing + multiline text' + /* hello */ +); + +$var = foo('Testing + multiline' + // hi + ) + foo('Testing + multiline' + // hi + ) +; + +class Test +{ + public function getInstance() + { + return new static( + 'arg', + 'foo' + ); + } + + public function getSelf() + { + return new self( + 'a', 'b', 'c' + ); + } +} + +$x = $var('y', + 'x'); + +$obj->{$x}(1, +2); + +(function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})( + 'a','b' +)('c', + 'd'); + +return trim(preg_replace_callback( + // sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) + // /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ + sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), + function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; + }, + $search + )); + +return trim(preg_replace_callback( +// sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) +// /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ +sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), +function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; +}, +$search +)); + +// PHP 8.0 named parameters. +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); + +array_fill_keys( + keys: range( 1, + 12, + ), value: true, +); + +// phpcs:set PSR2.Methods.FunctionCallSignature allowMultipleArguments true +array_fill_keys( + keys: range( 1, + 12, + ), value: true, +); +// phpcs:set PSR2.Methods.FunctionCallSignature allowMultipleArguments false diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc.fixed new file mode 100644 index 0000000..dc383ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.inc.fixed @@ -0,0 +1,283 @@ +get('/hello/{name}', function ($name) use ($app) { + return 'Hello '.$app->escape($name); +}, array( + '1', + '2', + '3', +)); + +// error +somefunction2( + $foo, + $bar, + [ + // ... + ], + $baz +); + +// ok +somefunction3(// ... + $foo, + $bar, + [ + // ... + ], + $baz +); + +// ok +somefunction4(' + this should not + give an error + because it\'s actually + one line call + with multi-line string +'); + +// ok +somefunction5("hey, +multi-line string with some +extra args", $foo, 12); + +// error +somefunction6( + ' + but args in a new line + are not ok… + ', + $foo +); + +$this->setFoo(true + ? 1 + : 2, false, array( + 'value', + 'more')); + +$this->setFoo('some' + . 'long' + . 'text', 'string'); + +foo(bar(), $a); +foo();bar(); + +foo( + true +); + +myFunction(<< function ($x) { + return true; + }, + 'baz' => false + ) +); +$qux = array_filter( + $quux, + function ($x) { + return $x; + } +); + +$this->listeners[] = $events->getSharedManager()->attach( + 'Zend\Mvc\Application', + MvcEvent::EVENT_DISPATCH, + [$this, 'selectLayout'], + 100 +); + +// phpcs:set PSR2.Methods.FunctionCallSignature requiredSpacesBeforeClose 1 +foo('Testing + multiline text' ); + +foo('Testing + multiline text: ' ); // . $text + + +foo('Testing + multiline text: ' /* . $text */ ); + +foo('Testing + multiline text: ' /* . $text */ ); + // . $other_text + + +foo('Testing + multiline text: ' /* + . $text +// . $text2 + */ ); +// phpcs:set PSR2.Methods.FunctionCallSignature requiredSpacesBeforeClose 0 + +foo('Testing + multiline text'); + +foo('Testing + multiline text'); + +foo('Testing + multiline text'); // hello + + +foo('Testing + multiline text' /* hello */); + +foo('Testing + multiline text'); + // hello + + +foo('Testing + multiline text' + /* hello */); + +$var = foo('Testing + multiline') + // hi + + foo('Testing + multiline'); + // hi + + +class Test +{ + public function getInstance() + { + return new static( + 'arg', + 'foo' + ); + } + + public function getSelf() + { + return new self( + 'a', + 'b', + 'c' + ); + } +} + +$x = $var( + 'y', + 'x' +); + +$obj->{$x}( + 1, + 2 +); + +(function ($a, $b) { + return function ($c, $d) use ($a, $b) { + echo $a, $b, $c, $d; + }; +})( + 'a', + 'b' +)( + 'c', + 'd' +); + +return trim(preg_replace_callback( + // sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) + // /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ + sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), + function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; + }, + $search +)); + +return trim(preg_replace_callback( +// sprintf replaces IGNORED_CHARS multiple times: for %s as well as %1$s (argument numbering) +// /[%s]*([^%1$s]+)/ results in /[IGNORED_CHARS]*([^IGNORED_CHARS]+)/ + sprintf('/[%s]*([^%1$s]+)/', self::IGNORED_CHARS), + function (array $term) use ($mode): string { + // query pieces have to bigger than one char, otherwise they are too expensive for the search + if (mb_strlen($term[1], 'UTF-8') > 1) { + // in boolean search mode '' (empty) means OR, '-' means NOT + return sprintf('%s%s ', $mode === 'AND' ? '+' : '', self::extractUmlauts($term[1])); + } + + return ''; + }, + $search +)); + +// PHP 8.0 named parameters. +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); + +array_fill_keys( + keys: range( + 1, + 12, + ), + value: true, +); + +// phpcs:set PSR2.Methods.FunctionCallSignature allowMultipleArguments true +array_fill_keys( + keys: range( + 1, + 12, + ), value: true, +); +// phpcs:set PSR2.Methods.FunctionCallSignature allowMultipleArguments false diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.php new file mode 100644 index 0000000..6abee06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionCallSignatureUnitTest.php @@ -0,0 +1,99 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Methods; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionCallSignature sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionCallSignatureSniff + */ +class FunctionCallSignatureUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 18 => 3, + 21 => 1, + 48 => 1, + 87 => 1, + 90 => 1, + 91 => 1, + 103 => 1, + 111 => 1, + 117 => 4, + 123 => 1, + 127 => 1, + 131 => 1, + 136 => 1, + 143 => 1, + 148 => 1, + 152 => 1, + 156 => 1, + 160 => 1, + 165 => 1, + 170 => 1, + 175 => 1, + 178 => 2, + 186 => 1, + 187 => 1, + 194 => 3, + 199 => 1, + 200 => 2, + 202 => 1, + 203 => 1, + 210 => 2, + 211 => 1, + 212 => 2, + 217 => 1, + 218 => 1, + 227 => 1, + 228 => 1, + 233 => 1, + 234 => 1, + 242 => 1, + 243 => 1, + 256 => 1, + 257 => 1, + 258 => 1, + 263 => 1, + 264 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionClosingBraceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionClosingBraceUnitTest.inc new file mode 100644 index 0000000..7bf667e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/FunctionClosingBraceUnitTest.inc @@ -0,0 +1,70 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Methods; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionClosingBrace sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionClosingBraceSniff + */ +class FunctionClosingBraceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 16 => 1, + 23 => 1, + 40 => 1, + 47 => 1, + 63 => 1, + 70 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/MethodDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/MethodDeclarationUnitTest.inc new file mode 100644 index 0000000..096b44b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Methods/MethodDeclarationUnitTest.inc @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Methods; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MethodDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\MethodDeclarationSniff + */ +class MethodDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 11 => 1, + 13 => 1, + 15 => 3, + 24 => 1, + 34 => 1, + 36 => 1, + 38 => 1, + 40 => 3, + 50 => 1, + 52 => 1, + 54 => 1, + 56 => 3, + 63 => 2, + 73 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 5 => 1, + 21 => 1, + 30 => 1, + 46 => 1, + 63 => 1, + 70 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/NamespaceDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/NamespaceDeclarationUnitTest.inc new file mode 100644 index 0000000..7033933 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/NamespaceDeclarationUnitTest.inc @@ -0,0 +1,26 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Namespaces; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the NamespaceDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces\NamespaceDeclarationSniff + */ +class NamespaceDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 6 => 1, + 9 => 1, + 17 => 1, + 19 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.1.inc new file mode 100644 index 0000000..61befc9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.1.inc @@ -0,0 +1,43 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.2.inc.fixed new file mode 100644 index 0000000..6579613 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.2.inc.fixed @@ -0,0 +1,27 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.3.inc new file mode 100644 index 0000000..8b29095 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.3.inc @@ -0,0 +1,16 @@ + +

    diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.5.inc new file mode 100644 index 0000000..1fdaccd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.5.inc @@ -0,0 +1,47 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.7.inc b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.7.inc new file mode 100644 index 0000000..dee5686 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests/Namespaces/UseDeclarationUnitTest.7.inc @@ -0,0 +1 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\PSR2\Tests\Namespaces; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the UseDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces\UseDeclarationSniff + */ +class UseDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'UseDeclarationUnitTest.2.inc': + return [ + 4 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 16 => 1, + ]; + case 'UseDeclarationUnitTest.3.inc': + return [ + 4 => 1, + 6 => 1, + ]; + case 'UseDeclarationUnitTest.5.inc': + return [ + 5 => 1, + 6 => 1, + 8 => 1, + 14 => 1, + 17 => 1, + 18 => 1, + 19 => 1, + 21 => 1, + 28 => 1, + 30 => 1, + 35 => 1, + ]; + case 'UseDeclarationUnitTest.10.inc': + case 'UseDeclarationUnitTest.11.inc': + case 'UseDeclarationUnitTest.12.inc': + case 'UseDeclarationUnitTest.13.inc': + case 'UseDeclarationUnitTest.14.inc': + case 'UseDeclarationUnitTest.16.inc': + case 'UseDeclarationUnitTest.17.inc': + return [2 => 1]; + case 'UseDeclarationUnitTest.15.inc': + return [ + 3 => 1, + 4 => 1, + 5 => 1, + ]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/ruleset.xml new file mode 100644 index 0000000..ba5bd4e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/PSR2/ruleset.xml @@ -0,0 +1,218 @@ + + + The PSR-2 coding standard. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + + + + + + + + + + + 0 + + + 0 + + + + + + + 0 + + + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayBracketSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayBracketSpacingStandard.xml new file mode 100644 index 0000000..fc6ccbd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayBracketSpacingStandard.xml @@ -0,0 +1,19 @@ + + + + + + + ['bar']; +]]> + + + [ 'bar' ]; +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayDeclarationStandard.xml new file mode 100644 index 0000000..ce4b9ae --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayDeclarationStandard.xml @@ -0,0 +1,117 @@ + + + + + + array keyword must be lowercase. + ]]> + + + + + + + + + + + array keyword. + ]]> + + + + 'value1', + 'key2' => 'value2', + ); + ]]> + + + 'value1', + 'key2' => 'value2', + ); + ]]> + + + + array keyword. The closing parenthesis must be aligned with the start of the array keyword. + ]]> + + + + 'key1' => 'value1', + 'key2' => 'value2', + ); + ]]> + + + 'key1' => 'value1', + 'key2' => 'value2', +); + ]]> + + + + + + + + => 'ValueTen', + 'keyTwenty' => 'ValueTwenty', + ); + ]]> + + + => 'ValueTen', + 'keyTwenty' => 'ValueTwenty', + ); + ]]> + + + + + + + + 'value1', + 'key2' => 'value2', + 'key3' => 'value3', + ); + ]]> + + + 'value1', + 'key2' => 'value2', + 'key3' => 'value3' + ); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/LowercaseClassKeywordsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/LowercaseClassKeywordsStandard.xml new file mode 100644 index 0000000..89fcb5d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/LowercaseClassKeywordsStandard.xml @@ -0,0 +1,23 @@ + + + + + + + final class Foo extends Bar +{ +} +]]> + + + Final Class Foo Extends Bar +{ +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/SelfMemberReferenceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/SelfMemberReferenceStandard.xml new file mode 100644 index 0000000..59d193f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/SelfMemberReferenceStandard.xml @@ -0,0 +1,63 @@ + + + + + + + self::foo(); +]]> + + + SELF::foo(); +]]> + + + + + ::foo(); +]]> + + + :: foo(); +]]> + + + + + self::bar(); + } +} +]]> + + + Foo +{ + public static function bar() + { + } + + public static function baz() + { + Foo::bar(); + } +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/DocCommentAlignmentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/DocCommentAlignmentStandard.xml new file mode 100644 index 0000000..414b89a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/DocCommentAlignmentStandard.xml @@ -0,0 +1,39 @@ + + + + + + + * @see foo() + */ +]]> + + + * @see foo() +*/ +]]> + + + + + @see foo() + */ +]]> + + + @see foo() + */ +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/FunctionCommentThrowTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/FunctionCommentThrowTagStandard.xml new file mode 100644 index 0000000..81df2e3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/FunctionCommentThrowTagStandard.xml @@ -0,0 +1,32 @@ + + + + + + + @throws Exception all the time + * @return void + */ +function foo() +{ + throw new Exception('Danger!'); +} +]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForEachLoopDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForEachLoopDeclarationStandard.xml new file mode 100644 index 0000000..87c6181 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForEachLoopDeclarationStandard.xml @@ -0,0 +1,39 @@ + + + + + + + $foo as $bar => $baz) { + echo $baz; +} +]]> + + + $foo as $bar=>$baz ) { + echo $baz; +} +]]> + + + + + as $bar => $baz) { + echo $baz; +} +]]> + + + AS $bar => $baz) { + echo $baz; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForLoopDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForLoopDeclarationStandard.xml new file mode 100644 index 0000000..bbc4392 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForLoopDeclarationStandard.xml @@ -0,0 +1,55 @@ + + + + + + + $i = 0; $i < 10; $i++) { + echo $i; +} +]]> + + + $i = 0; $i < 10; $i++ ) { + echo $i; +} +]]> + + + + + ; $i < 10; $i++) { + echo $i; +} +]]> + + + ; $i < 10 ; $i++) { + echo $i; +} +]]> + + + + + $i < 10; $i++) { + echo $i; +} +]]> + + + $i < 10;$i++) { + echo $i; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/LowercaseDeclarationStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/LowercaseDeclarationStandard.xml new file mode 100644 index 0000000..699f1f0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/LowercaseDeclarationStandard.xml @@ -0,0 +1,23 @@ + + + + + + + if ($foo) { + $bar = true; +} +]]> + + + IF ($foo) { + $bar = true; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/FunctionDuplicateArgumentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/FunctionDuplicateArgumentStandard.xml new file mode 100644 index 0000000..a890aba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/FunctionDuplicateArgumentStandard.xml @@ -0,0 +1,23 @@ + + + + + + + isset($foo)) { + echo $foo; +} +]]> + + + isSet($foo)) { + echo $foo; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/LowercaseFunctionKeywordsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/LowercaseFunctionKeywordsStandard.xml new file mode 100644 index 0000000..46e8a8f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/LowercaseFunctionKeywordsStandard.xml @@ -0,0 +1,25 @@ + + + + + + + function foo() +{ + return true; +} +]]> + + + FUNCTION foo() +{ + return true; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Scope/StaticThisUsageStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Scope/StaticThisUsageStandard.xml new file mode 100644 index 0000000..3c97f54 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Scope/StaticThisUsageStandard.xml @@ -0,0 +1,31 @@ + + + + + + + static function bar() + { + return self::$staticMember; + } +} +]]> + + + static function bar() + { + return $this->$staticMember; + } +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Strings/EchoedStringsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Strings/EchoedStringsStandard.xml new file mode 100644 index 0000000..030f2a6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Strings/EchoedStringsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + "Hello"; +]]> + + + ("Hello"); +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/CastSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/CastSpacingStandard.xml new file mode 100644 index 0000000..0fb195c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/CastSpacingStandard.xml @@ -0,0 +1,19 @@ + + + + + + + int)'42'; +]]> + + + int )'42'; +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/FunctionOpeningBraceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/FunctionOpeningBraceStandard.xml new file mode 100644 index 0000000..d2bc264 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/FunctionOpeningBraceStandard.xml @@ -0,0 +1,41 @@ + + + + + + + { +} +]]> + + + { +} +]]> + + + + + return 42; +} +]]> + + + + return 42; +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml new file mode 100644 index 0000000..608bed0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml @@ -0,0 +1,19 @@ + + + + + + + "hi"; +]]> + + + "hi"; +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ObjectOperatorSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ObjectOperatorSpacingStandard.xml new file mode 100644 index 0000000..c6194d7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ObjectOperatorSpacingStandard.xml @@ -0,0 +1,19 @@ + + + ) should not have any space around it. + ]]> + + + + ->bar(); +]]> + + + -> bar(); +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ScopeKeywordSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ScopeKeywordSpacingStandard.xml new file mode 100644 index 0000000..8cadf66 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ScopeKeywordSpacingStandard.xml @@ -0,0 +1,23 @@ + + + + + + + static function foo() +{ +} +]]> + + + static function foo() +{ +} +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/SemicolonSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/SemicolonSpacingStandard.xml new file mode 100644 index 0000000..7b22795 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/SemicolonSpacingStandard.xml @@ -0,0 +1,19 @@ + + + + + + + ; +]]> + + + ; +]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayBracketSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayBracketSpacingSniff.php new file mode 100644 index 0000000..b6bb31d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayBracketSpacingSniff.php @@ -0,0 +1,95 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ArrayBracketSpacingSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_SQUARE_BRACKET, + T_CLOSE_SQUARE_BRACKET, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (($tokens[$stackPtr]['code'] === T_OPEN_SQUARE_BRACKET + && isset($tokens[$stackPtr]['bracket_closer']) === false) + || ($tokens[$stackPtr]['code'] === T_CLOSE_SQUARE_BRACKET + && isset($tokens[$stackPtr]['bracket_opener']) === false) + ) { + // Bow out for parse error/during live coding. + return; + } + + // Square brackets can not have a space before them. + $prevType = $tokens[($stackPtr - 1)]['code']; + if ($prevType === T_WHITESPACE) { + $nonSpace = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 2), null, true); + $expected = $tokens[$nonSpace]['content'].$tokens[$stackPtr]['content']; + $found = $phpcsFile->getTokensAsString($nonSpace, ($stackPtr - $nonSpace)).$tokens[$stackPtr]['content']; + $error = 'Space found before square bracket; expected "%s" but found "%s"'; + $data = [ + $expected, + $found, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeBracket', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ''); + } + } + + // Open square brackets can't ever have spaces after them. + if ($tokens[$stackPtr]['code'] === T_OPEN_SQUARE_BRACKET) { + $nextType = $tokens[($stackPtr + 1)]['code']; + if ($nextType === T_WHITESPACE) { + $nonSpace = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 2), null, true); + $expected = $tokens[$stackPtr]['content'].$tokens[$nonSpace]['content']; + $found = $phpcsFile->getTokensAsString($stackPtr, ($nonSpace - $stackPtr + 1)); + $error = 'Space found after square bracket; expected "%s" but found "%s"'; + $data = [ + $expected, + $found, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterBracket', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php new file mode 100644 index 0000000..9cd4198 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php @@ -0,0 +1,938 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ArrayDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_ARRAY, + T_OPEN_SHORT_ARRAY, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_ARRAY) { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no'); + + // Array keyword should be lower case. + if ($tokens[$stackPtr]['content'] !== strtolower($tokens[$stackPtr]['content'])) { + if ($tokens[$stackPtr]['content'] === strtoupper($tokens[$stackPtr]['content'])) { + $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'upper'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'mixed'); + } + + $error = 'Array keyword should be lower case; expected "array" but found "%s"'; + $data = [$tokens[$stackPtr]['content']]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotLowerCase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'array'); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Array keyword case', 'lower'); + } + + $arrayStart = $tokens[$stackPtr]['parenthesis_opener']; + if (isset($tokens[$arrayStart]['parenthesis_closer']) === false) { + return; + } + + $arrayEnd = $tokens[$arrayStart]['parenthesis_closer']; + + if ($arrayStart !== ($stackPtr + 1)) { + $error = 'There must be no space between the "array" keyword and the opening parenthesis'; + + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $arrayStart, true); + if (isset(Tokens::$commentTokens[$tokens[$next]['code']]) === true) { + // We don't have anywhere to put the comment, so don't attempt to fix it. + $phpcsFile->addError($error, $stackPtr, 'SpaceAfterKeyword'); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterKeyword'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($stackPtr + 1); $i < $arrayStart; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); + $arrayStart = $stackPtr; + $arrayEnd = $tokens[$stackPtr]['bracket_closer']; + }//end if + + // Check for empty arrays. + $content = $phpcsFile->findNext(T_WHITESPACE, ($arrayStart + 1), ($arrayEnd + 1), true); + if ($content === $arrayEnd) { + // Empty array, but if the brackets aren't together, there's a problem. + if (($arrayEnd - $arrayStart) !== 1) { + $error = 'Empty array declaration must have no space between the parentheses'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceInEmptyArray'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + // We can return here because there is nothing else to check. All code + // below can assume that the array is not empty. + return; + } + + if ($tokens[$arrayStart]['line'] === $tokens[$arrayEnd]['line']) { + $this->processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd); + } else { + $this->processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd); + } + + }//end process() + + + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * + * @return void + */ + public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd) + { + $tokens = $phpcsFile->getTokens(); + + // Check if there are multiple values. If so, then it has to be multiple lines + // unless it is contained inside a function call or condition. + $valueCount = 0; + $commas = []; + for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { + // Skip bracketed statements, like function calls. + if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) { + $i = $tokens[$i]['parenthesis_closer']; + continue; + } + + if ($tokens[$i]['code'] === T_COMMA) { + // Before counting this comma, make sure we are not + // at the end of the array. + $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $arrayEnd, true); + if ($next !== false) { + $valueCount++; + $commas[] = $i; + } else { + // There is a comma at the end of a single line array. + $error = 'Comma not allowed after last value in single-line array declaration'; + $fix = $phpcsFile->addFixableError($error, $i, 'CommaAfterLast'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + } + }//end for + + // Now check each of the double arrows (if any). + $nextArrow = $arrayStart; + while (($nextArrow = $phpcsFile->findNext(T_DOUBLE_ARROW, ($nextArrow + 1), $arrayEnd)) !== false) { + if ($tokens[($nextArrow - 1)]['code'] !== T_WHITESPACE) { + $content = $tokens[($nextArrow - 1)]['content']; + $error = 'Expected 1 space between "%s" and double arrow; 0 found'; + $data = [$content]; + $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceBeforeDoubleArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($nextArrow, ' '); + } + } else { + $spaceLength = $tokens[($nextArrow - 1)]['length']; + if ($spaceLength !== 1) { + $content = $tokens[($nextArrow - 2)]['content']; + $error = 'Expected 1 space between "%s" and double arrow; %s found'; + $data = [ + $content, + $spaceLength, + ]; + + $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceBeforeDoubleArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($nextArrow - 1), ' '); + } + } + }//end if + + if ($tokens[($nextArrow + 1)]['code'] !== T_WHITESPACE) { + $content = $tokens[($nextArrow + 1)]['content']; + $error = 'Expected 1 space between double arrow and "%s"; 0 found'; + $data = [$content]; + $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceAfterDoubleArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($nextArrow, ' '); + } + } else { + $spaceLength = $tokens[($nextArrow + 1)]['length']; + if ($spaceLength !== 1) { + $content = $tokens[($nextArrow + 2)]['content']; + $error = 'Expected 1 space between double arrow and "%s"; %s found'; + $data = [ + $content, + $spaceLength, + ]; + + $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceAfterDoubleArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($nextArrow + 1), ' '); + } + } + }//end if + }//end while + + if ($valueCount > 0) { + $nestedParenthesis = false; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $nested = $tokens[$stackPtr]['nested_parenthesis']; + $nestedParenthesis = array_pop($nested); + } + + if ($nestedParenthesis === false + || $tokens[$nestedParenthesis]['line'] !== $tokens[$stackPtr]['line'] + ) { + $error = 'Array with multiple values cannot be declared on a single line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SingleLineNotAllowed'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($arrayStart); + + if ($tokens[($arrayEnd - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($arrayEnd - 1), $phpcsFile->eolChar); + } else { + $phpcsFile->fixer->addNewlineBefore($arrayEnd); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + } + + // We have a multiple value array that is inside a condition or + // function. Check its spacing is correct. + foreach ($commas as $comma) { + if ($tokens[($comma + 1)]['code'] !== T_WHITESPACE) { + $content = $tokens[($comma + 1)]['content']; + $error = 'Expected 1 space between comma and "%s"; 0 found'; + $data = [$content]; + $fix = $phpcsFile->addFixableError($error, $comma, 'NoSpaceAfterComma', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($comma, ' '); + } + } else { + $spaceLength = $tokens[($comma + 1)]['length']; + if ($spaceLength !== 1) { + $content = $tokens[($comma + 2)]['content']; + $error = 'Expected 1 space between comma and "%s"; %s found'; + $data = [ + $content, + $spaceLength, + ]; + + $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceAfterComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($comma + 1), ' '); + } + } + }//end if + + if ($tokens[($comma - 1)]['code'] === T_WHITESPACE) { + $content = $tokens[($comma - 2)]['content']; + $spaceLength = $tokens[($comma - 1)]['length']; + $error = 'Expected 0 spaces between "%s" and comma; %s found'; + $data = [ + $content, + $spaceLength, + ]; + + $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($comma - 1), ''); + } + } + }//end foreach + }//end if + + }//end processSingleLineArray() + + + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * + * @return void + */ + public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd) + { + $tokens = $phpcsFile->getTokens(); + $keywordStart = $tokens[$stackPtr]['column']; + + // Check the closing bracket is on a new line. + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($arrayEnd - 1), $arrayStart, true); + if ($tokens[$lastContent]['line'] === $tokens[$arrayEnd]['line']) { + $error = 'Closing parenthesis of array declaration must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNewLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($arrayEnd); + } + } else if ($tokens[$arrayEnd]['column'] !== $keywordStart) { + // Check the closing bracket is lined up under the "a" in array. + $expected = ($keywordStart - 1); + $found = ($tokens[$arrayEnd]['column'] - 1); + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Closing parenthesis not aligned correctly; expected %s space%s but found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNotAligned', $data); + if ($fix === true) { + if ($found === 0) { + $phpcsFile->fixer->addContent(($arrayEnd - 1), str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($arrayEnd - 1), str_repeat(' ', $expected)); + } + } + }//end if + + $keyUsed = false; + $singleUsed = false; + $indices = []; + $maxLength = 0; + + if ($tokens[$stackPtr]['code'] === T_ARRAY) { + $lastToken = $tokens[$stackPtr]['parenthesis_opener']; + } else { + $lastToken = $stackPtr; + } + + // Find all the double arrows that reside in this scope. + for ($nextToken = ($stackPtr + 1); $nextToken < $arrayEnd; $nextToken++) { + // Skip bracketed statements, like function calls. + if ($tokens[$nextToken]['code'] === T_OPEN_PARENTHESIS + && (isset($tokens[$nextToken]['parenthesis_owner']) === false + || $tokens[$nextToken]['parenthesis_owner'] !== $stackPtr) + ) { + $nextToken = $tokens[$nextToken]['parenthesis_closer']; + continue; + } + + if ($tokens[$nextToken]['code'] === T_ARRAY + || $tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY + || $tokens[$nextToken]['code'] === T_CLOSURE + || $tokens[$nextToken]['code'] === T_FN + || $tokens[$nextToken]['code'] === T_MATCH + ) { + // Let subsequent calls of this test handle nested arrays. + if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) { + $indices[] = ['value' => $nextToken]; + $lastToken = $nextToken; + } + + if ($tokens[$nextToken]['code'] === T_ARRAY) { + $nextToken = $tokens[$tokens[$nextToken]['parenthesis_opener']]['parenthesis_closer']; + } else if ($tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY) { + $nextToken = $tokens[$nextToken]['bracket_closer']; + } else { + // T_CLOSURE. + $nextToken = $tokens[$nextToken]['scope_closer']; + } + + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] !== T_COMMA) { + $nextToken--; + } else { + $lastToken = $nextToken; + } + + continue; + }//end if + + if ($tokens[$nextToken]['code'] !== T_DOUBLE_ARROW && $tokens[$nextToken]['code'] !== T_COMMA) { + continue; + } + + $currentEntry = []; + + if ($tokens[$nextToken]['code'] === T_COMMA) { + $stackPtrCount = 0; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $stackPtrCount = count($tokens[$stackPtr]['nested_parenthesis']); + } + + $commaCount = 0; + if (isset($tokens[$nextToken]['nested_parenthesis']) === true) { + $commaCount = count($tokens[$nextToken]['nested_parenthesis']); + if ($tokens[$stackPtr]['code'] === T_ARRAY) { + // Remove parenthesis that are used to define the array. + $commaCount--; + } + } + + if ($commaCount > $stackPtrCount) { + // This comma is inside more parenthesis than the ARRAY keyword, + // then there it is actually a comma used to separate arguments + // in a function call. + continue; + } + + if ($keyUsed === true && $tokens[$lastToken]['code'] === T_COMMA) { + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($lastToken + 1), null, true); + // Allow for PHP 7.4+ array unpacking within an array declaration. + if ($tokens[$nextToken]['code'] !== T_ELLIPSIS) { + $error = 'No key specified for array entry; first entry specifies key'; + $phpcsFile->addError($error, $nextToken, 'NoKeySpecified'); + return; + } + } + + if ($keyUsed === false) { + if ($tokens[($nextToken - 1)]['code'] === T_WHITESPACE) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($nextToken - 1), null, true); + if (($tokens[$prev]['code'] !== T_END_HEREDOC + && $tokens[$prev]['code'] !== T_END_NOWDOC) + || $tokens[($nextToken - 1)]['line'] === $tokens[$nextToken]['line'] + ) { + if ($tokens[($nextToken - 1)]['content'] === $phpcsFile->eolChar) { + $spaceLength = 'newline'; + } else { + $spaceLength = $tokens[($nextToken - 1)]['length']; + } + + $error = 'Expected 0 spaces before comma; %s found'; + $data = [$spaceLength]; + + // The error is only fixable if there is only whitespace between the tokens. + if ($prev === $phpcsFile->findPrevious(T_WHITESPACE, ($nextToken - 1), null, true)) { + $fix = $phpcsFile->addFixableError($error, $nextToken, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($nextToken - 1), ''); + } + } else { + $phpcsFile->addError($error, $nextToken, 'SpaceBeforeComma', $data); + } + } + }//end if + + $valueContent = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($lastToken + 1), + $nextToken, + true + ); + + $indices[] = ['value' => $valueContent]; + $usesArrayUnpacking = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($nextToken - 2), + null, + true + ); + if ($tokens[$usesArrayUnpacking]['code'] !== T_ELLIPSIS) { + // Don't decide if an array is key => value indexed or not when PHP 7.4+ array unpacking is used. + $singleUsed = true; + } + }//end if + + $lastToken = $nextToken; + continue; + }//end if + + if ($tokens[$nextToken]['code'] === T_DOUBLE_ARROW) { + if ($singleUsed === true) { + $error = 'Key specified for array entry; first entry has no key'; + $phpcsFile->addError($error, $nextToken, 'KeySpecified'); + return; + } + + $currentEntry['arrow'] = $nextToken; + $keyUsed = true; + + // Find the start of index that uses this double arrow. + $indexEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($nextToken - 1), $arrayStart, true); + $indexStart = $phpcsFile->findStartOfStatement($indexEnd); + + if ($indexStart === $indexEnd) { + $currentEntry['index'] = $indexEnd; + $currentEntry['index_content'] = $tokens[$indexEnd]['content']; + $currentEntry['index_length'] = $tokens[$indexEnd]['length']; + } else { + $currentEntry['index'] = $indexStart; + $currentEntry['index_content'] = ''; + $currentEntry['index_length'] = 0; + for ($i = $indexStart; $i <= $indexEnd; $i++) { + $currentEntry['index_content'] .= $tokens[$i]['content']; + $currentEntry['index_length'] += $tokens[$i]['length']; + } + } + + if ($maxLength < $currentEntry['index_length']) { + $maxLength = $currentEntry['index_length']; + } + + // Find the value of this index. + $nextContent = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($nextToken + 1), + $arrayEnd, + true + ); + + $currentEntry['value'] = $nextContent; + $indices[] = $currentEntry; + $lastToken = $nextToken; + }//end if + }//end for + + // Check for multi-line arrays that should be single-line. + $singleValue = false; + + if (empty($indices) === true) { + $singleValue = true; + } else if (count($indices) === 1 && $tokens[$lastToken]['code'] === T_COMMA) { + // There may be another array value without a comma. + $exclude = Tokens::$emptyTokens; + $exclude[] = T_COMMA; + $nextContent = $phpcsFile->findNext($exclude, ($indices[0]['value'] + 1), $arrayEnd, true); + if ($nextContent === false) { + $singleValue = true; + } + } + + if ($singleValue === true) { + // Before we complain, make sure the single value isn't a here/nowdoc. + $next = $phpcsFile->findNext(Tokens::$heredocTokens, ($arrayStart + 1), ($arrayEnd - 1)); + if ($next === false) { + // Array cannot be empty, so this is a multi-line array with + // a single value. It should be defined on single line. + $error = 'Multi-line array contains a single value; use single-line array instead'; + $errorCode = 'MultiLineNotAllowed'; + + $find = Tokens::$phpcsCommentTokens; + $find[] = T_COMMENT; + $comment = $phpcsFile->findNext($find, ($arrayStart + 1), $arrayEnd); + if ($comment === false) { + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode); + } else { + $fix = false; + $phpcsFile->addError($error, $stackPtr, $errorCode); + } + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + for ($i = ($arrayEnd - 1); $i > $arrayStart; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + }//end if + }//end if + + /* + This section checks for arrays that don't specify keys. + + Arrays such as: + array( + 'aaa', + 'bbb', + 'd', + ); + */ + + if ($keyUsed === false && empty($indices) === false) { + $count = count($indices); + $lastIndex = $indices[($count - 1)]['value']; + + $trailingContent = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($arrayEnd - 1), + $lastIndex, + true + ); + + if ($tokens[$trailingContent]['code'] !== T_COMMA) { + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no'); + $error = 'Comma required after last value in array declaration'; + $fix = $phpcsFile->addFixableError($error, $trailingContent, 'NoCommaAfterLast'); + if ($fix === true) { + $phpcsFile->fixer->addContent($trailingContent, ','); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes'); + } + + foreach ($indices as $valuePosition => $value) { + if (empty($value['value']) === true) { + // Array was malformed and we couldn't figure out + // the array value correctly, so we have to ignore it. + // Other parts of this sniff will correct the error. + continue; + } + + $valuePointer = $value['value']; + + $ignoreTokens = [ + T_WHITESPACE => T_WHITESPACE, + T_COMMA => T_COMMA, + ]; + $ignoreTokens += Tokens::$castTokens; + + if ($tokens[$valuePointer]['code'] === T_CLOSURE + || $tokens[$valuePointer]['code'] === T_FN + ) { + $ignoreTokens += [T_STATIC => T_STATIC]; + } + + $previous = $phpcsFile->findPrevious($ignoreTokens, ($valuePointer - 1), ($arrayStart + 1), true); + if ($previous === false) { + $previous = $stackPtr; + } + + $previousIsWhitespace = $tokens[($valuePointer - 1)]['code'] === T_WHITESPACE; + if ($tokens[$previous]['line'] === $tokens[$valuePointer]['line']) { + $error = 'Each value in a multi-line array must be on a new line'; + if ($valuePosition === 0) { + $error = 'The first value in a multi-value array must be on a new line'; + } + + $fix = $phpcsFile->addFixableError($error, $valuePointer, 'ValueNoNewline'); + if ($fix === true) { + if ($previousIsWhitespace === true) { + $phpcsFile->fixer->replaceToken(($valuePointer - 1), $phpcsFile->eolChar); + } else { + $phpcsFile->fixer->addNewlineBefore($valuePointer); + } + } + } else if ($previousIsWhitespace === true) { + $expected = $keywordStart; + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $valuePointer, true); + $found = ($tokens[$first]['column'] - 1); + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + if ($found !== $expected) { + $error = 'Array value not aligned correctly; expected %s space%s but found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $first, 'ValueNotAligned', $data); + if ($fix === true) { + if ($found === 0) { + $phpcsFile->fixer->addContent(($first - 1), str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($first - 1), str_repeat(' ', $expected)); + } + } + } + }//end if + }//end foreach + }//end if + + /* + Below the actual indentation of the array is checked. + Errors will be thrown when a key is not aligned, when + a double arrow is not aligned, and when a value is not + aligned correctly. + If an error is found in one of the above areas, then errors + are not reported for the rest of the line to avoid reporting + spaces and columns incorrectly. Often fixing the first + problem will fix the other 2 anyway. + + For example: + + $a = array( + 'index' => '2', + ); + + or + + $a = [ + 'index' => '2', + ]; + + In this array, the double arrow is indented too far, but this + will also cause an error in the value's alignment. If the arrow were + to be moved back one space however, then both errors would be fixed. + */ + + $indicesStart = ($keywordStart + 1); + foreach ($indices as $valuePosition => $index) { + $valuePointer = $index['value']; + if ($valuePointer === false) { + // Syntax error or live coding. + continue; + } + + if (isset($index['index']) === false) { + // Array value only. + continue; + } + + $indexPointer = $index['index']; + $indexLine = $tokens[$indexPointer]['line']; + + $previous = $phpcsFile->findPrevious([T_WHITESPACE, T_COMMA], ($indexPointer - 1), ($arrayStart + 1), true); + if ($previous === false) { + $previous = $stackPtr; + } + + if ($tokens[$previous]['line'] === $indexLine) { + $error = 'Each index in a multi-line array must be on a new line'; + if ($valuePosition === 0) { + $error = 'The first index in a multi-value array must be on a new line'; + } + + $fix = $phpcsFile->addFixableError($error, $indexPointer, 'IndexNoNewline'); + if ($fix === true) { + if ($tokens[($indexPointer - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($indexPointer - 1), $phpcsFile->eolChar); + } else { + $phpcsFile->fixer->addNewlineBefore($indexPointer); + } + } + + continue; + } + + if ($tokens[$indexPointer]['column'] !== $indicesStart && ($indexPointer - 1) !== $arrayStart) { + $expected = ($indicesStart - 1); + $found = ($tokens[$indexPointer]['column'] - 1); + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array key not aligned correctly; expected %s space%s but found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $indexPointer, 'KeyNotAligned', $data); + if ($fix === true) { + if ($found === 0 || $tokens[($indexPointer - 1)]['code'] !== T_WHITESPACE) { + $phpcsFile->fixer->addContent(($indexPointer - 1), str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($indexPointer - 1), str_repeat(' ', $expected)); + } + } + }//end if + + $arrowStart = ($tokens[$indexPointer]['column'] + $maxLength + 1); + if ($tokens[$index['arrow']]['column'] !== $arrowStart) { + $expected = ($arrowStart - ($index['index_length'] + $tokens[$indexPointer]['column'])); + $found = ($tokens[$index['arrow']]['column'] - ($index['index_length'] + $tokens[$indexPointer]['column'])); + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array double arrow not aligned correctly; expected %s space%s but found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'DoubleArrowNotAligned', $data); + if ($fix === true) { + if ($found === 0) { + $phpcsFile->fixer->addContent(($index['arrow'] - 1), str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($index['arrow'] - 1), str_repeat(' ', $expected)); + } + } + + continue; + }//end if + + $valueStart = ($arrowStart + 3); + if ($tokens[$valuePointer]['column'] !== $valueStart) { + $expected = ($valueStart - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); + $found = ($tokens[$valuePointer]['column'] - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); + if ($found < 0) { + $found = 'newline'; + } + + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Array value not aligned correctly; expected %s space%s but found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'ValueNotAligned', $data); + if ($fix === true) { + if ($found === 'newline') { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($valuePointer - 1), null, true); + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $valuePointer; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken(($valuePointer - 1), str_repeat(' ', $expected)); + $phpcsFile->fixer->endChangeset(); + } else if ($found === 0) { + $phpcsFile->fixer->addContent(($valuePointer - 1), str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($valuePointer - 1), str_repeat(' ', $expected)); + } + } + }//end if + + // Check each line ends in a comma. + $valueStart = $valuePointer; + $nextComma = false; + + $end = $phpcsFile->findEndOfStatement($valueStart); + if ($end === false) { + $valueEnd = $valueStart; + } else if ($tokens[$end]['code'] === T_COMMA) { + $valueEnd = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($end - 1), $valueStart, true); + $nextComma = $end; + } else { + $valueEnd = $end; + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $arrayEnd, true); + if ($next !== false && $tokens[$next]['code'] === T_COMMA) { + $nextComma = $next; + } + } + + $valueLine = $tokens[$valueEnd]['line']; + if ($tokens[$valueEnd]['code'] === T_END_HEREDOC || $tokens[$valueEnd]['code'] === T_END_NOWDOC) { + $valueLine++; + } + + if ($nextComma === false || ($tokens[$nextComma]['line'] !== $valueLine)) { + $error = 'Each line in an array declaration must end in a comma'; + $fix = $phpcsFile->addFixableError($error, $valuePointer, 'NoComma'); + + if ($fix === true) { + // Find the end of the line and put a comma there. + for ($i = ($valuePointer + 1); $i <= $arrayEnd; $i++) { + if ($tokens[$i]['line'] > $valueLine) { + break; + } + } + + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore(($i - 1), ','); + if ($nextComma !== false) { + $phpcsFile->fixer->replaceToken($nextComma, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + // Check that there is no space before the comma. + if ($nextComma !== false && $tokens[($nextComma - 1)]['code'] === T_WHITESPACE) { + // Here/nowdoc closing tags must have the comma on the next line. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($nextComma - 1), null, true); + if ($tokens[$prev]['code'] !== T_END_HEREDOC && $tokens[$prev]['code'] !== T_END_NOWDOC) { + $content = $tokens[($nextComma - 2)]['content']; + $spaceLength = $tokens[($nextComma - 1)]['length']; + $error = 'Expected 0 spaces between "%s" and comma; %s found'; + $data = [ + $content, + $spaceLength, + ]; + + $fix = $phpcsFile->addFixableError($error, $nextComma, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($nextComma - 1), ''); + } + } + } + }//end foreach + + }//end processMultiLineArray() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionClosingBraceSpaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionClosingBraceSpaceSniff.php new file mode 100644 index 0000000..fb14758 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionClosingBraceSpaceSniff.php @@ -0,0 +1,134 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassDefinitionClosingBraceSpaceSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_CLOSE_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $next = $stackPtr; + while (true) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($next + 1), null, true); + if ($next === false) { + return; + } + + if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === true + && $tokens[$next]['line'] === $tokens[$stackPtr]['line'] + ) { + // Trailing comment. + continue; + } + + break; + } + + if ($tokens[$next]['code'] !== T_CLOSE_TAG) { + $found = (($tokens[$next]['line'] - $tokens[$stackPtr]['line']) - 1); + if ($found !== 1) { + $error = 'Expected one blank line after closing brace of class definition; %s found'; + $data = [max(0, $found)]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterClose', $data); + + if ($fix === true) { + $firstOnLine = $next; + while ($tokens[$firstOnLine]['column'] !== 1) { + --$firstOnLine; + } + + if ($found < 0) { + // Next statement on same line as the closing brace. + $phpcsFile->fixer->addContentBefore($next, $phpcsFile->eolChar.$phpcsFile->eolChar); + } else if ($found === 0) { + // Next statement on next line, no blank line. + $phpcsFile->fixer->addContentBefore($firstOnLine, $phpcsFile->eolChar); + } else { + // Too many blank lines. + $phpcsFile->fixer->beginChangeset(); + for ($i = ($firstOnLine - 1); $i > $stackPtr; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addContentBefore($firstOnLine, $phpcsFile->eolChar.$phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + }//end if + + // Ignore nested style definitions from here on. The spacing before the closing brace + // (a single blank line) will be enforced by the above check, which ensures there is a + // blank line after the last nested class. + $found = $phpcsFile->findPrevious( + T_CLOSE_CURLY_BRACKET, + ($stackPtr - 1), + $tokens[$stackPtr]['bracket_opener'] + ); + + if ($found !== false) { + return; + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($prev === false) { + return; + } + + if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']) { + $error = 'Closing brace of class definition must be on new line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentBeforeClose'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($stackPtr); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionNameSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionNameSpacingSniff.php new file mode 100644 index 0000000..7ed872f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionNameSpacingSniff.php @@ -0,0 +1,111 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassDefinitionNameSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['bracket_closer']) === false) { + // Syntax error or live coding, bow out. + return; + } + + // Do not check nested style definitions as, for example, in @media style rules. + $nested = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($stackPtr + 1), $tokens[$stackPtr]['bracket_closer']); + if ($nested !== false) { + return; + } + + // Find the first blank line before this opening brace, unless we get + // to another style definition, comment or the start of the file. + $endTokens = [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_OPEN_TAG => T_OPEN_TAG, + ]; + $endTokens += Tokens::$commentTokens; + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + + $foundContent = false; + $currentLine = $tokens[$prev]['line']; + for ($i = ($stackPtr - 1); $i >= 0; $i--) { + if (isset($endTokens[$tokens[$i]['code']]) === true) { + break; + } + + if ($tokens[$i]['line'] === $currentLine) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + $foundContent = true; + } + + continue; + } + + // We changed lines. + if ($foundContent === false) { + // Before we throw an error, make sure we are not looking + // at a gap before the style definition. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, $i, null, true); + if ($prev !== false + && isset($endTokens[$tokens[$prev]['code']]) === false + ) { + $error = 'Blank lines are not allowed between class names'; + $phpcsFile->addError($error, ($i + 1), 'BlankLinesFound'); + } + + break; + } + + $foundContent = false; + $currentLine = $tokens[$i]['line']; + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionOpeningBraceSpaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionOpeningBraceSpaceSniff.php new file mode 100644 index 0000000..0b84fa6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionOpeningBraceSpaceSniff.php @@ -0,0 +1,176 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassDefinitionOpeningBraceSpaceSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + + if ($prevNonWhitespace !== false) { + $length = 0; + if ($tokens[$stackPtr]['line'] !== $tokens[$prevNonWhitespace]['line']) { + $length = 'newline'; + } else if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + if (strpos($tokens[($stackPtr - 1)]['content'], "\t") !== false) { + $length = 'tab'; + } else { + $length = $tokens[($stackPtr - 1)]['length']; + } + } + + if ($length === 0) { + $error = 'Expected 1 space before opening brace of class definition; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoneBefore'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + } else if ($length !== 1) { + $error = 'Expected 1 space before opening brace of class definition; %s found'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($stackPtr - 1); $i > $prevNonWhitespace; $i--) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($nextNonEmpty === false) { + return; + } + + if ($tokens[$nextNonEmpty]['line'] === $tokens[$stackPtr]['line']) { + $error = 'Opening brace should be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentBefore'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($stackPtr); + + // Remove potentially left over trailing whitespace. + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + if (isset($tokens[$stackPtr]['bracket_closer']) === false) { + // Syntax error or live coding, bow out. + return; + } + + // Check for nested class definitions. + $found = $phpcsFile->findNext( + T_OPEN_CURLY_BRACKET, + ($stackPtr + 1), + $tokens[$stackPtr]['bracket_closer'] + ); + + if ($found === false) { + // Not nested. + return; + } + + $lastOnLine = $stackPtr; + for ($lastOnLine; $lastOnLine < $tokens[$stackPtr]['bracket_closer']; $lastOnLine++) { + if ($tokens[$lastOnLine]['line'] !== $tokens[($lastOnLine + 1)]['line']) { + break; + } + } + + $nextNonWhiteSpace = $phpcsFile->findNext(T_WHITESPACE, ($lastOnLine + 1), null, true); + if ($nextNonWhiteSpace === false) { + return; + } + + $foundLines = ($tokens[$nextNonWhiteSpace]['line'] - $tokens[$stackPtr]['line'] - 1); + if ($foundLines !== 1) { + $error = 'Expected 1 blank line after opening brace of nesting class definition; %s found'; + $data = [max(0, $foundLines)]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'AfterNesting', $data); + + if ($fix === true) { + $firstOnNextLine = $nextNonWhiteSpace; + while ($tokens[$firstOnNextLine]['column'] !== 1) { + --$firstOnNextLine; + } + + if ($found < 0) { + // First statement on same line as the opening brace. + $phpcsFile->fixer->addContentBefore($nextNonWhiteSpace, $phpcsFile->eolChar.$phpcsFile->eolChar); + } else if ($found === 0) { + // Next statement on next line, no blank line. + $phpcsFile->fixer->addNewlineBefore($firstOnNextLine); + } else { + // Too many blank lines. + $phpcsFile->fixer->beginChangeset(); + for ($i = ($firstOnNextLine - 1); $i > $stackPtr; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addContentBefore($firstOnNextLine, $phpcsFile->eolChar.$phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColonSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColonSpacingSniff.php new file mode 100644 index 0000000..07b6088 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColonSpacingSniff.php @@ -0,0 +1,107 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ColonSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_COLON]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] !== T_STYLE) { + // The colon is not part of a style definition. + return; + } + + if ($tokens[$prev]['content'] === 'progid') { + // Special case for IE filters. + return; + } + + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + $error = 'There must be no space before a colon in a style definition'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ''); + } + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_SEMICOLON || $tokens[$next]['code'] === T_STYLE) { + // Empty style definition, ignore it. + return; + } + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space after colon in style definition; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoneAfter'); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + } else { + $content = $tokens[($stackPtr + 1)]['content']; + if (strpos($content, $phpcsFile->eolChar) === false) { + $length = strlen($content); + if ($length !== 1) { + $error = 'Expected 1 space after colon in style definition; %s found'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'After', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } else { + $error = 'Expected 1 space after colon in style definition; newline found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'AfterNewline'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColourDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColourDefinitionSniff.php new file mode 100644 index 0000000..0f9131e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColourDefinitionSniff.php @@ -0,0 +1,88 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ColourDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_COLOUR]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $colour = $tokens[$stackPtr]['content']; + + $expected = strtoupper($colour); + if ($colour !== $expected) { + $error = 'CSS colours must be defined in uppercase; expected %s but found %s'; + $data = [ + $expected, + $colour, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotUpper', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $expected); + } + } + + // Now check if shorthand can be used. + if (strlen($colour) !== 7) { + return; + } + + if ($colour[1] === $colour[2] && $colour[3] === $colour[4] && $colour[5] === $colour[6]) { + $expected = '#'.$colour[1].$colour[3].$colour[5]; + $error = 'CSS colours must use shorthand if available; expected %s but found %s'; + $data = [ + $expected, + $colour, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Shorthand', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $expected); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DisallowMultipleStyleDefinitionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DisallowMultipleStyleDefinitionsSniff.php new file mode 100644 index 0000000..ddea314 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DisallowMultipleStyleDefinitionsSniff.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowMultipleStyleDefinitionsSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var string[] + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $next = $phpcsFile->findNext(T_STYLE, ($stackPtr + 1)); + if ($next === false) { + return; + } + + if ($tokens[$next]['content'] === 'progid') { + // Special case for IE filters. + return; + } + + if ($tokens[$next]['line'] === $tokens[$stackPtr]['line']) { + $error = 'Each style definition must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $next, 'Found'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($next); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateClassDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateClassDefinitionSniff.php new file mode 100644 index 0000000..b1c81bd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateClassDefinitionSniff.php @@ -0,0 +1,116 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DuplicateClassDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Find the content of each class definition name. + $classNames = []; + $next = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($stackPtr + 1)); + if ($next === false) { + // No class definitions in the file. + return; + } + + // Save the class names in a "scope", + // to prevent false positives with @media blocks. + $scope = 'main'; + + $find = [ + T_CLOSE_CURLY_BRACKET, + T_OPEN_CURLY_BRACKET, + T_OPEN_TAG, + ]; + + while ($next !== false) { + $prev = $phpcsFile->findPrevious($find, ($next - 1)); + + // Check if an inner block was closed. + $beforePrev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true); + if ($beforePrev !== false + && $tokens[$beforePrev]['code'] === T_CLOSE_CURLY_BRACKET + ) { + $scope = 'main'; + } + + // Create a sorted name for the class so we can compare classes + // even when the individual names are all over the place. + $name = ''; + for ($i = ($prev + 1); $i < $next; $i++) { + $name .= $tokens[$i]['content']; + } + + $name = trim($name); + $name = str_replace("\n", ' ', $name); + $name = preg_replace('|[\s]+|', ' ', $name); + $name = preg_replace('|\s*/\*.*\*/\s*|', '', $name); + $name = str_replace(', ', ',', $name); + + $names = explode(',', $name); + sort($names); + $name = implode(',', $names); + + if ($name[0] === '@') { + // Media block has its own "scope". + $scope = $name; + } else if (isset($classNames[$scope][$name]) === true) { + $first = $classNames[$scope][$name]; + $error = 'Duplicate class definition found; first defined on line %s'; + $data = [$tokens[$first]['line']]; + $phpcsFile->addError($error, $next, 'Found', $data); + } else { + $classNames[$scope][$name] = $next; + } + + $next = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($next + 1)); + }//end while + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateStyleDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateStyleDefinitionSniff.php new file mode 100644 index 0000000..97ad572 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateStyleDefinitionSniff.php @@ -0,0 +1,88 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DuplicateStyleDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['bracket_closer']) === false) { + // Syntax error or live coding, bow out. + return; + } + + // Find the content of each style definition name. + $styleNames = []; + + $next = $stackPtr; + $end = $tokens[$stackPtr]['bracket_closer']; + + do { + $next = $phpcsFile->findNext([T_STYLE, T_OPEN_CURLY_BRACKET], ($next + 1), $end); + if ($next === false) { + // Class definition is empty. + break; + } + + if ($tokens[$next]['code'] === T_OPEN_CURLY_BRACKET) { + $next = $tokens[$next]['bracket_closer']; + continue; + } + + $name = $tokens[$next]['content']; + if (isset($styleNames[$name]) === true) { + $first = $styleNames[$name]; + $error = 'Duplicate style definition found; first defined on line %s'; + $data = [$tokens[$first]['line']]; + $phpcsFile->addError($error, $next, 'Found', $data); + } else { + $styleNames[$name] = $next; + } + } while ($next !== false); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyClassDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyClassDefinitionSniff.php new file mode 100644 index 0000000..e641ed2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyClassDefinitionSniff.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EmptyClassDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + + if ($next === false || $tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) { + $error = 'Class definition is empty'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyStyleDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyStyleDefinitionSniff.php new file mode 100644 index 0000000..816bb9b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyStyleDefinitionSniff.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EmptyStyleDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $ignore = Tokens::$emptyTokens; + $ignore[] = T_COLON; + + $next = $phpcsFile->findNext($ignore, ($stackPtr + 1), null, true); + if ($next === false || $tokens[$next]['code'] === T_SEMICOLON || $tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + $error = 'Style definition is empty'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ForbiddenStylesSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ForbiddenStylesSniff.php new file mode 100644 index 0000000..b695596 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ForbiddenStylesSniff.php @@ -0,0 +1,177 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ForbiddenStylesSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + /** + * A list of forbidden styles with their alternatives. + * + * The value is NULL if no alternative exists. i.e., the + * style should just not be used. + * + * @var array + */ + protected $forbiddenStyles = [ + '-moz-border-radius' => 'border-radius', + '-webkit-border-radius' => 'border-radius', + '-moz-border-radius-topleft' => 'border-top-left-radius', + '-moz-border-radius-topright' => 'border-top-right-radius', + '-moz-border-radius-bottomright' => 'border-bottom-right-radius', + '-moz-border-radius-bottomleft' => 'border-bottom-left-radius', + '-moz-box-shadow' => 'box-shadow', + '-webkit-box-shadow' => 'box-shadow', + ]; + + /** + * A cache of forbidden style names, for faster lookups. + * + * @var string[] + */ + protected $forbiddenStyleNames = []; + + /** + * If true, forbidden styles will be considered regular expressions. + * + * @var boolean + */ + protected $patternMatch = false; + + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = true; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $this->forbiddenStyleNames = array_keys($this->forbiddenStyles); + + if ($this->patternMatch === true) { + foreach ($this->forbiddenStyleNames as $i => $name) { + $this->forbiddenStyleNames[$i] = '/'.$name.'/i'; + } + } + + return [T_STYLE]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $style = strtolower($tokens[$stackPtr]['content']); + $pattern = null; + + if ($this->patternMatch === true) { + $count = 0; + $pattern = preg_replace( + $this->forbiddenStyleNames, + $this->forbiddenStyleNames, + $style, + 1, + $count + ); + + if ($count === 0) { + return; + } + + // Remove the pattern delimiters and modifier. + $pattern = substr($pattern, 1, -2); + } else { + if (in_array($style, $this->forbiddenStyleNames, true) === false) { + return; + } + }//end if + + $this->addError($phpcsFile, $stackPtr, $style, $pattern); + + }//end process() + + + /** + * Generates the error or warning for this sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the forbidden style + * in the token array. + * @param string $style The name of the forbidden style. + * @param string $pattern The pattern used for the match. + * + * @return void + */ + protected function addError($phpcsFile, $stackPtr, $style, $pattern=null) + { + $data = [$style]; + $error = 'The use of style %s is '; + if ($this->error === true) { + $type = 'Found'; + $error .= 'forbidden'; + } else { + $type = 'Discouraged'; + $error .= 'discouraged'; + } + + if ($pattern === null) { + $pattern = $style; + } + + if ($this->forbiddenStyles[$pattern] !== null) { + $data[] = $this->forbiddenStyles[$pattern]; + if ($this->error === true) { + $fix = $phpcsFile->addFixableError($error.'; use %s instead', $stackPtr, $type.'WithAlternative', $data); + } else { + $fix = $phpcsFile->addFixableWarning($error.'; use %s instead', $stackPtr, $type.'WithAlternative', $data); + } + + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $this->forbiddenStyles[$pattern]); + } + } else { + if ($this->error === true) { + $phpcsFile->addError($error, $stackPtr, $type, $data); + } else { + $phpcsFile->addWarning($error, $stackPtr, $type, $data); + } + } + + }//end addError() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/IndentationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/IndentationSniff.php new file mode 100644 index 0000000..427468c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/IndentationSniff.php @@ -0,0 +1,150 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class IndentationSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $numTokens = (count($tokens) - 2); + $indentLevel = 0; + $nestingLevel = 0; + for ($i = 1; $i < $numTokens; $i++) { + if ($tokens[$i]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$i]['code']]) === true + ) { + // Don't check the indent of comments. + continue; + } + + if ($tokens[$i]['code'] === T_OPEN_CURLY_BRACKET) { + $indentLevel++; + + if (isset($tokens[$i]['bracket_closer']) === false) { + // Syntax error or live coding. + // Anything after this would receive incorrect fixes, so bow out. + return; + } + + // Check for nested class definitions. + $found = $phpcsFile->findNext( + T_OPEN_CURLY_BRACKET, + ($i + 1), + $tokens[$i]['bracket_closer'] + ); + + if ($found !== false) { + $nestingLevel = $indentLevel; + } + } + + if (($tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET + && $tokens[$i]['line'] !== $tokens[($i - 1)]['line']) + || ($tokens[($i + 1)]['code'] === T_CLOSE_CURLY_BRACKET + && $tokens[$i]['line'] === $tokens[($i + 1)]['line']) + ) { + $indentLevel--; + if ($indentLevel === 0) { + $nestingLevel = 0; + } + } + + if ($tokens[$i]['column'] !== 1 + || $tokens[$i]['code'] === T_OPEN_CURLY_BRACKET + || $tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET + ) { + continue; + } + + // We started a new line, so check indent. + if ($tokens[$i]['code'] === T_WHITESPACE) { + $content = str_replace($phpcsFile->eolChar, '', $tokens[$i]['content']); + $foundIndent = strlen($content); + } else { + $foundIndent = 0; + } + + $expectedIndent = ($indentLevel * $this->indent); + if ($expectedIndent > 0 + && strpos($tokens[$i]['content'], $phpcsFile->eolChar) !== false + ) { + if ($nestingLevel !== $indentLevel) { + $error = 'Blank lines are not allowed in class definitions'; + $fix = $phpcsFile->addFixableError($error, $i, 'BlankLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + } else if ($foundIndent !== $expectedIndent) { + $error = 'Line indented incorrectly; expected %s spaces, found %s'; + $data = [ + $expectedIndent, + $foundIndent, + ]; + + $fix = $phpcsFile->addFixableError($error, $i, 'Incorrect', $data); + if ($fix === true) { + $indent = str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($i, $indent); + } else { + $phpcsFile->fixer->replaceToken($i, $indent); + } + } + }//end if + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/LowercaseStyleDefinitionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/LowercaseStyleDefinitionSniff.php new file mode 100644 index 0000000..509e986 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/LowercaseStyleDefinitionSniff.php @@ -0,0 +1,97 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class LowercaseStyleDefinitionSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = ($stackPtr + 1); + $end = ($tokens[$stackPtr]['bracket_closer'] - 1); + $inStyle = null; + + for ($i = $start; $i <= $end; $i++) { + // Skip nested definitions as they are checked individually. + if ($tokens[$i]['code'] === T_OPEN_CURLY_BRACKET) { + $i = $tokens[$i]['bracket_closer']; + continue; + } + + if ($tokens[$i]['code'] === T_STYLE) { + $inStyle = $tokens[$i]['content']; + } + + if ($tokens[$i]['code'] === T_SEMICOLON) { + $inStyle = null; + } + + if ($inStyle === 'progid') { + // Special case for IE filters. + continue; + } + + if ($tokens[$i]['code'] === T_STYLE + || ($inStyle !== null + && $tokens[$i]['code'] === T_STRING) + ) { + $expected = strtolower($tokens[$i]['content']); + if ($expected !== $tokens[$i]['content']) { + $error = 'Style definitions must be lowercase; expected %s but found %s'; + $data = [ + $expected, + $tokens[$i]['content'], + ]; + + $fix = $phpcsFile->addFixableError($error, $i, 'FoundUpper', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($i, $expected); + } + } + } + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/MissingColonSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/MissingColonSniff.php new file mode 100644 index 0000000..a9ca371 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/MissingColonSniff.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class MissingColonSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['bracket_closer']) === false) { + // Syntax error or live coding, bow out. + return; + } + + $lastLine = $tokens[$stackPtr]['line']; + $end = $tokens[$stackPtr]['bracket_closer']; + + // Do not check nested style definitions as, for example, in @media style rules. + $nested = $phpcsFile->findNext(T_OPEN_CURLY_BRACKET, ($stackPtr + 1), $end); + if ($nested !== false) { + return; + } + + $foundColon = false; + $foundString = false; + for ($i = ($stackPtr + 1); $i <= $end; $i++) { + if ($tokens[$i]['line'] !== $lastLine) { + // We changed lines. + if ($foundColon === false && $foundString !== false) { + // We didn't find a colon on the previous line. + $error = 'No style definition found on line; check for missing colon'; + $phpcsFile->addError($error, $foundString, 'Found'); + } + + $foundColon = false; + $foundString = false; + $lastLine = $tokens[$i]['line']; + } + + if ($tokens[$i]['code'] === T_STRING) { + $foundString = $i; + } else if ($tokens[$i]['code'] === T_COLON) { + $foundColon = $i; + } + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/NamedColoursSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/NamedColoursSniff.php new file mode 100644 index 0000000..9322ef8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/NamedColoursSniff.php @@ -0,0 +1,93 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class NamedColoursSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + /** + * A list of named colours. + * + * This is the list of standard colours defined in the CSS specification. + * + * @var array + */ + protected $colourNames = [ + 'aqua' => 'aqua', + 'black' => 'black', + 'blue' => 'blue', + 'fuchsia' => 'fuchsia', + 'gray' => 'gray', + 'green' => 'green', + 'lime' => 'lime', + 'maroon' => 'maroon', + 'navy' => 'navy', + 'olive' => 'olive', + 'orange' => 'orange', + 'purple' => 'purple', + 'red' => 'red', + 'silver' => 'silver', + 'teal' => 'teal', + 'white' => 'white', + 'yellow' => 'yellow', + ]; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STRING]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[($stackPtr - 1)]['code'] === T_HASH + || $tokens[($stackPtr - 1)]['code'] === T_STRING_CONCAT + ) { + // Class name. + return; + } + + if (isset($this->colourNames[strtolower($tokens[$stackPtr]['content'])]) === true) { + $error = 'Named colours are forbidden; use hex, rgb, or rgba values instead'; + $phpcsFile->addError($error, $stackPtr, 'Forbidden'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/OpacitySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/OpacitySniff.php new file mode 100644 index 0000000..e2a3e8d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/OpacitySniff.php @@ -0,0 +1,101 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OpacitySniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['content'] !== 'opacity') { + return; + } + + $ignore = Tokens::$emptyTokens; + $ignore[] = T_COLON; + + $next = $phpcsFile->findNext($ignore, ($stackPtr + 1), null, true); + + if ($next === false + || ($tokens[$next]['code'] !== T_DNUMBER + && $tokens[$next]['code'] !== T_LNUMBER) + ) { + return; + } + + $value = $tokens[$next]['content']; + if ($tokens[$next]['code'] === T_LNUMBER) { + if ($value !== '0' && $value !== '1') { + $error = 'Opacity values must be between 0 and 1'; + $phpcsFile->addError($error, $next, 'Invalid'); + } + } else { + if (strlen($value) > 3) { + $error = 'Opacity values must have a single value after the decimal point'; + $phpcsFile->addError($error, $next, 'DecimalPrecision'); + } else if ($value === '0.0' || $value === '1.0') { + $error = 'Opacity value does not require decimal point; use %s instead'; + $data = [$value[0]]; + $fix = $phpcsFile->addFixableError($error, $next, 'PointNotRequired', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($next, $value[0]); + } + } else if ($value[0] === '.') { + $error = 'Opacity values must not start with a decimal point; use 0%s instead'; + $data = [$value]; + $fix = $phpcsFile->addFixableError($error, $next, 'StartWithPoint', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($next, '0'.$value); + } + } else if ($value[0] !== '0') { + $error = 'Opacity values must be between 0 and 1'; + $phpcsFile->addError($error, $next, 'Invalid'); + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/SemicolonSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/SemicolonSpacingSniff.php new file mode 100644 index 0000000..ef9d238 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/SemicolonSpacingSniff.php @@ -0,0 +1,103 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SemicolonSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $nextStatement = $phpcsFile->findNext([T_STYLE, T_CLOSE_CURLY_BRACKET], ($stackPtr + 1)); + if ($nextStatement === false) { + return; + } + + $ignore = Tokens::$emptyTokens; + if ($tokens[$nextStatement]['code'] === T_STYLE) { + // Allow for star-prefix hack. + $ignore[] = T_MULTIPLY; + } + + $endOfThisStatement = $phpcsFile->findPrevious($ignore, ($nextStatement - 1), null, true); + if ($tokens[$endOfThisStatement]['code'] !== T_SEMICOLON) { + $error = 'Style definitions must end with a semicolon'; + $phpcsFile->addError($error, $endOfThisStatement, 'NotAtEnd'); + return; + } + + if ($tokens[($endOfThisStatement - 1)]['code'] !== T_WHITESPACE) { + return; + } + + // There is a semi-colon, so now find the last token in the statement. + $prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($endOfThisStatement - 1), null, true); + $found = $tokens[($endOfThisStatement - 1)]['length']; + if ($tokens[$prevNonEmpty]['line'] !== $tokens[$endOfThisStatement]['line']) { + $found = 'newline'; + } + + $error = 'Expected 0 spaces before semicolon in style definition; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $prevNonEmpty, 'SpaceFound', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($prevNonEmpty, ';'); + $phpcsFile->fixer->replaceToken($endOfThisStatement, ''); + + for ($i = ($endOfThisStatement - 1); $i > $prevNonEmpty; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ShorthandSizeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ShorthandSizeSniff.php new file mode 100644 index 0000000..b59c279 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ShorthandSizeSniff.php @@ -0,0 +1,181 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ShorthandSizeSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + + /** + * A list of styles that we shouldn't check. + * + * These have values that looks like sizes, but are not. + * + * @var array + */ + protected $excludeStyles = [ + 'background-position' => 'background-position', + 'box-shadow' => 'box-shadow', + 'transform-origin' => 'transform-origin', + '-webkit-transform-origin' => '-webkit-transform-origin', + '-ms-transform-origin' => '-ms-transform-origin', + ]; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_STYLE]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Some styles look like shorthand but are not actually a set of 4 sizes. + $style = strtolower($tokens[$stackPtr]['content']); + if (isset($this->excludeStyles[$style]) === true) { + return; + } + + $end = $phpcsFile->findNext(T_SEMICOLON, ($stackPtr + 1)); + if ($end === false) { + // Live coding or parse error. + return; + } + + // Get the whole style content. + $origContent = $phpcsFile->getTokensAsString(($stackPtr + 1), ($end - $stackPtr - 1)); + $origContent = trim($origContent, ':'); + $origContent = trim($origContent); + + // Account for a !important annotation. + $content = $origContent; + if (substr($content, -10) === '!important') { + $content = substr($content, 0, -10); + $content = trim($content); + } + + // Check if this style value is a set of numbers with optional prefixes. + $content = preg_replace('/\s+/', ' ', $content); + $values = []; + $num = preg_match_all( + '/(?:[0-9]+)(?:[a-zA-Z]{2}\s+|%\s+|\s+)/', + $content.' ', + $values, + PREG_SET_ORDER + ); + + // Only interested in styles that have multiple sizes defined. + if ($num < 2) { + return; + } + + // Rebuild the content we matched to ensure we got everything. + $matched = ''; + foreach ($values as $value) { + $matched .= $value[0]; + } + + if ($content !== trim($matched)) { + return; + } + + if ($num === 3) { + $expected = trim($content.' '.$values[1][0]); + $error = 'Shorthand syntax not allowed here; use %s instead'; + $data = [$expected]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAllowed', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + if (substr($origContent, -10) === '!important') { + $expected .= ' !important'; + } + + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 2), null, true); + $phpcsFile->fixer->replaceToken($next, $expected); + for ($next++; $next < $end; $next++) { + $phpcsFile->fixer->replaceToken($next, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + }//end if + + if ($num === 2) { + if ($values[0][0] !== $values[1][0]) { + // Both values are different, so it is already shorthand. + return; + } + } else if ($values[0][0] !== $values[2][0] || $values[1][0] !== $values[3][0]) { + // Can't shorthand this. + return; + } + + if ($values[0][0] === $values[1][0]) { + // All values are the same. + $expected = trim($values[0][0]); + } else { + $expected = trim($values[0][0]).' '.trim($values[1][0]); + } + + $error = 'Size definitions must use shorthand if available; expected "%s" but found "%s"'; + $data = [ + $expected, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotUsed', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + if (substr($origContent, -10) === '!important') { + $expected .= ' !important'; + } + + $next = $phpcsFile->findNext(T_COLON, ($stackPtr + 1)); + $phpcsFile->fixer->addContent($next, ' '.$expected); + for ($next++; $next < $end; $next++) { + $phpcsFile->fixer->replaceToken($next, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php new file mode 100644 index 0000000..3f5e1fb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php @@ -0,0 +1,207 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff as PSR2ClassDeclarationSniff; +use PHP_CodeSniffer\Util\Tokens; + +class ClassDeclarationSniff extends PSR2ClassDeclarationSniff +{ + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // We want all the errors from the PSR2 standard, plus some of our own. + parent::process($phpcsFile, $stackPtr); + + // Check that this is the only class or interface in the file. + $nextClass = $phpcsFile->findNext([T_CLASS, T_INTERFACE], ($stackPtr + 1)); + if ($nextClass !== false) { + // We have another, so an error is thrown. + $error = 'Only one interface or class is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleClasses'); + } + + }//end process() + + + /** + * Processes the opening section of a class declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processOpen(File $phpcsFile, $stackPtr) + { + parent::processOpen($phpcsFile, $stackPtr); + + $tokens = $phpcsFile->getTokens(); + + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + $prevContent = $tokens[($stackPtr - 1)]['content']; + if ($prevContent !== $phpcsFile->eolChar) { + $blankSpace = substr($prevContent, strpos($prevContent, $phpcsFile->eolChar)); + $spaces = strlen($blankSpace); + + if ($tokens[($stackPtr - 2)]['code'] !== T_ABSTRACT + && $tokens[($stackPtr - 2)]['code'] !== T_FINAL + && $tokens[($stackPtr - 2)]['code'] !== T_READONLY + ) { + if ($spaces !== 0) { + $type = strtolower($tokens[$stackPtr]['content']); + $error = 'Expected 0 spaces before %s keyword; %s found'; + $data = [ + $type, + $spaces, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeKeyword', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ''); + } + } + } + }//end if + }//end if + + }//end processOpen() + + + /** + * Processes the closing section of a class declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processClose(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $closeBrace = $tokens[$stackPtr]['scope_closer']; + + // Check that the closing brace has one blank line after it. + for ($nextContent = ($closeBrace + 1); $nextContent < $phpcsFile->numTokens; $nextContent++) { + // Ignore comments on the same line as the brace. + if ($tokens[$nextContent]['line'] === $tokens[$closeBrace]['line'] + && ($tokens[$nextContent]['code'] === T_WHITESPACE + || $tokens[$nextContent]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$nextContent]['code']]) === true) + ) { + continue; + } + + if ($tokens[$nextContent]['code'] !== T_WHITESPACE) { + break; + } + } + + if ($nextContent === $phpcsFile->numTokens) { + // Ignore the line check as this is the very end of the file. + $difference = 1; + } else { + $difference = ($tokens[$nextContent]['line'] - $tokens[$closeBrace]['line'] - 1); + } + + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBrace - 1), $stackPtr, true); + + if ($difference === -1 + || $tokens[$lastContent]['line'] === $tokens[$closeBrace]['line'] + ) { + $error = 'Closing %s brace must be on a line by itself'; + $data = [$tokens[$stackPtr]['content']]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'CloseBraceSameLine', $data); + if ($fix === true) { + if ($difference === -1) { + $phpcsFile->fixer->addNewlineBefore($nextContent); + } + + if ($tokens[$lastContent]['line'] === $tokens[$closeBrace]['line']) { + $phpcsFile->fixer->addNewlineBefore($closeBrace); + } + } + } else if ($tokens[($closeBrace - 1)]['code'] === T_WHITESPACE) { + $prevContent = $tokens[($closeBrace - 1)]['content']; + if ($prevContent !== $phpcsFile->eolChar) { + $blankSpace = substr($prevContent, strpos($prevContent, $phpcsFile->eolChar)); + $spaces = strlen($blankSpace); + if ($spaces !== 0) { + if ($tokens[($closeBrace - 1)]['line'] !== $tokens[$closeBrace]['line']) { + $error = 'Expected 0 spaces before closing brace; newline found'; + $phpcsFile->addError($error, $closeBrace, 'NewLineBeforeCloseBrace'); + } else { + $error = 'Expected 0 spaces before closing brace; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpaceBeforeCloseBrace', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($closeBrace - 1), ''); + } + } + } + } + }//end if + + if ($difference !== -1 && $difference !== 1) { + if ($tokens[$nextContent]['code'] === T_DOC_COMMENT_OPEN_TAG) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($tokens[$nextContent]['comment_closer'] + 1), null, true); + if ($next !== false && $tokens[$next]['code'] === T_FUNCTION) { + return; + } + } + + $error = 'Closing brace of a %s must be followed by a single blank line; found %s'; + $data = [ + $tokens[$stackPtr]['content'], + $difference, + ]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'NewlinesAfterCloseBrace', $data); + if ($fix === true) { + if ($difference === 0) { + $first = $phpcsFile->findFirstOnLine([], $nextContent, true); + $phpcsFile->fixer->addNewlineBefore($first); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($closeBrace + 1); $i < $nextContent; $i++) { + if ($tokens[$i]['line'] <= ($tokens[$closeBrace]['line'] + 1)) { + continue; + } else if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end processClose() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassFileNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassFileNameSniff.php new file mode 100644 index 0000000..fc3ec04 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassFileNameSniff.php @@ -0,0 +1,70 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClassFileNameSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $fullPath = basename($phpcsFile->getFilename()); + $fileName = substr($fullPath, 0, strrpos($fullPath, '.')); + if ($fileName === '') { + // No filename probably means STDIN, so we can't do this check. + return; + } + + $tokens = $phpcsFile->getTokens(); + $decName = $phpcsFile->findNext(T_STRING, $stackPtr); + + if ($tokens[$decName]['content'] !== $fileName) { + $error = '%s name doesn\'t match filename; expected "%s %s"'; + $data = [ + ucfirst($tokens[$stackPtr]['content']), + $tokens[$stackPtr]['content'], + $fileName, + ]; + $phpcsFile->addError($error, $stackPtr, 'NoMatch', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/DuplicatePropertySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/DuplicatePropertySniff.php new file mode 100644 index 0000000..0493b77 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/DuplicatePropertySniff.php @@ -0,0 +1,82 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DuplicatePropertySniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OBJECT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being processed. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $properties = []; + $wantedTokens = [ + T_PROPERTY, + T_OBJECT, + ]; + + $next = $phpcsFile->findNext($wantedTokens, ($stackPtr + 1), $tokens[$stackPtr]['bracket_closer']); + while ($next !== false && $next < $tokens[$stackPtr]['bracket_closer']) { + if ($tokens[$next]['code'] === T_OBJECT) { + // Skip nested objects. + $next = $tokens[$next]['bracket_closer']; + } else { + $propName = $tokens[$next]['content']; + if (isset($properties[$propName]) === true) { + $error = 'Duplicate property definition found for "%s"; previously defined on line %s'; + $data = [ + $propName, + $tokens[$properties[$propName]]['line'], + ]; + $phpcsFile->addError($error, $next, 'Found', $data); + } + + $properties[$propName] = $next; + }//end if + + $next = $phpcsFile->findNext($wantedTokens, ($next + 1), $tokens[$stackPtr]['bracket_closer']); + }//end while + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/LowercaseClassKeywordsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/LowercaseClassKeywordsSniff.php new file mode 100644 index 0000000..b9d71db --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/LowercaseClassKeywordsSniff.php @@ -0,0 +1,73 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class LowercaseClassKeywordsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $targets = Tokens::$ooScopeTokens; + $targets[] = T_EXTENDS; + $targets[] = T_IMPLEMENTS; + $targets[] = T_ABSTRACT; + $targets[] = T_FINAL; + $targets[] = T_READONLY; + $targets[] = T_VAR; + $targets[] = T_CONST; + + return $targets; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $contentLc = strtolower($content); + if ($content !== $contentLc) { + $error = '%s keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + strtoupper($content), + $contentLc, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FoundUppercase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $contentLc); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/SelfMemberReferenceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/SelfMemberReferenceSniff.php new file mode 100644 index 0000000..407d3da --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/SelfMemberReferenceSniff.php @@ -0,0 +1,240 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Tokens; + +class SelfMemberReferenceSniff extends AbstractScopeSniff +{ + + + /** + * Constructs a Squiz_Sniffs_Classes_SelfMemberReferenceSniff. + */ + public function __construct() + { + parent::__construct([T_CLASS], [T_DOUBLE_COLON]); + + }//end __construct() + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * @param int $currScope The current scope opener token. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a double colon which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + $conditions = array_reverse($conditions, true); + foreach ($conditions as $conditionToken => $tokenCode) { + if ($tokenCode === T_CLASS || $tokenCode === T_ANON_CLASS || $tokenCode === T_CLOSURE) { + break; + } + } + + if ($conditionToken !== $currScope) { + return; + } + + $calledClassName = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($calledClassName === false) { + // Parse error. + return; + } + + if ($tokens[$calledClassName]['code'] === T_SELF) { + if ($tokens[$calledClassName]['content'] !== 'self') { + $error = 'Must use "self::" for local static member reference; found "%s::"'; + $data = [$tokens[$calledClassName]['content']]; + $fix = $phpcsFile->addFixableError($error, $calledClassName, 'IncorrectCase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($calledClassName, 'self'); + } + + return; + } + } else if ($tokens[$calledClassName]['code'] === T_STRING) { + // If the class is called with a namespace prefix, build fully qualified + // namespace calls for both current scope class and requested class. + $prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($calledClassName - 1), null, true); + if ($prevNonEmpty !== false && $tokens[$prevNonEmpty]['code'] === T_NS_SEPARATOR) { + $declarationName = $this->getDeclarationNameWithNamespace($tokens, $calledClassName); + $declarationName = ltrim($declarationName, '\\'); + $fullQualifiedClassName = $this->getNamespaceOfScope($phpcsFile, $currScope); + if ($fullQualifiedClassName === '\\') { + $fullQualifiedClassName = ''; + } else { + $fullQualifiedClassName .= '\\'; + } + + $fullQualifiedClassName .= $phpcsFile->getDeclarationName($currScope); + } else { + $declarationName = $phpcsFile->getDeclarationName($currScope); + $fullQualifiedClassName = $tokens[$calledClassName]['content']; + } + + if ($declarationName === $fullQualifiedClassName) { + // Class name is the same as the current class, which is not allowed. + $error = 'Must use "self::" for local static member reference'; + $fix = $phpcsFile->addFixableError($error, $calledClassName, 'NotUsed'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + $currentPointer = ($stackPtr - 1); + while ($tokens[$currentPointer]['code'] === T_NS_SEPARATOR + || $tokens[$currentPointer]['code'] === T_STRING + || isset(Tokens::$emptyTokens[$tokens[$currentPointer]['code']]) === true + ) { + if (isset(Tokens::$emptyTokens[$tokens[$currentPointer]['code']]) === true) { + --$currentPointer; + continue; + } + + $phpcsFile->fixer->replaceToken($currentPointer, ''); + --$currentPointer; + } + + $phpcsFile->fixer->replaceToken($stackPtr, 'self::'); + $phpcsFile->fixer->endChangeset(); + + // Fix potential whitespace issues in the next loop. + return; + }//end if + }//end if + }//end if + + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + $found = $tokens[($stackPtr - 1)]['length']; + $error = 'Expected 0 spaces before double colon; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, ($stackPtr - 1), 'SpaceBefore', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($stackPtr - 1); $tokens[$i]['code'] === T_WHITESPACE; $i--) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $found = $tokens[($stackPtr + 1)]['length']; + $error = 'Expected 0 spaces after double colon; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, ($stackPtr - 1), 'SpaceAfter', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($stackPtr + 1); $tokens[$i]['code'] === T_WHITESPACE; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + }//end processTokenWithinScope() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + + /** + * Returns the declaration names for classes/interfaces/functions with a namespace. + * + * @param array $tokens Token stack for this file + * @param int $stackPtr The position where the namespace building will start. + * + * @return string + */ + protected function getDeclarationNameWithNamespace(array $tokens, $stackPtr) + { + $nameParts = []; + $currentPointer = $stackPtr; + while ($tokens[$currentPointer]['code'] === T_NS_SEPARATOR + || $tokens[$currentPointer]['code'] === T_STRING + || isset(Tokens::$emptyTokens[$tokens[$currentPointer]['code']]) === true + ) { + if (isset(Tokens::$emptyTokens[$tokens[$currentPointer]['code']]) === true) { + --$currentPointer; + continue; + } + + $nameParts[] = $tokens[$currentPointer]['content']; + --$currentPointer; + } + + $nameParts = array_reverse($nameParts); + return implode('', $nameParts); + + }//end getDeclarationNameWithNamespace() + + + /** + * Returns the namespace declaration of a file. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the search for the + * namespace declaration will start. + * + * @return string + */ + protected function getNamespaceOfScope(File $phpcsFile, $stackPtr) + { + $namespace = '\\'; + $namespaceDeclaration = $phpcsFile->findPrevious(T_NAMESPACE, $stackPtr); + + if ($namespaceDeclaration !== false) { + $endOfNamespaceDeclaration = $phpcsFile->findNext([T_SEMICOLON, T_OPEN_CURLY_BRACKET], $namespaceDeclaration); + $namespace = $this->getDeclarationNameWithNamespace( + $phpcsFile->getTokens(), + ($endOfNamespaceDeclaration - 1) + ); + } + + return $namespace; + + }//end getNamespaceOfScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php new file mode 100644 index 0000000..a897535 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php @@ -0,0 +1,87 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class ValidClassNameSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being processed. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $data); + return; + } + + // Determine the name of the class or interface. Note that we cannot + // simply look for the first T_STRING because a class name + // starting with the number will be multiple tokens. + $opener = $tokens[$stackPtr]['scope_opener']; + $nameStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $opener, true); + $nameEnd = $phpcsFile->findNext([T_WHITESPACE, T_COLON], $nameStart, $opener); + if ($nameEnd === false) { + $name = $tokens[$nameStart]['content']; + } else { + $name = trim($phpcsFile->getTokensAsString($nameStart, ($nameEnd - $nameStart))); + } + + // Check for PascalCase format. + $valid = Common::isCamelCaps($name, true, true, false); + if ($valid === false) { + $type = ucfirst($tokens[$stackPtr]['content']); + $error = '%s name "%s" is not in PascalCase format'; + $data = [ + $type, + $name, + ]; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); + $phpcsFile->recordMetric($stackPtr, 'PascalCase class name', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'PascalCase class name', 'yes'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php new file mode 100644 index 0000000..9a56512 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php @@ -0,0 +1,401 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class BlockCommentSniff implements Sniff +{ + + /** + * The --tab-width CLI value that is being used. + * + * @var integer + */ + private $tabWidth = null; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_COMMENT, + T_DOC_COMMENT_OPEN_TAG, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($this->tabWidth === null) { + if (isset($phpcsFile->config->tabWidth) === false || $phpcsFile->config->tabWidth === 0) { + // We have no idea how wide tabs are, so assume 4 spaces for fixing. + $this->tabWidth = 4; + } else { + $this->tabWidth = $phpcsFile->config->tabWidth; + } + } + + $tokens = $phpcsFile->getTokens(); + + // If it's an inline comment, return. + if (substr($tokens[$stackPtr]['content'], 0, 2) !== '/*') { + return; + } + + // If this is a function/class/interface doc block comment, skip it. + // We are only interested in inline doc block comments. + if ($tokens[$stackPtr]['code'] === T_DOC_COMMENT_OPEN_TAG) { + $nextToken = $stackPtr; + do { + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] === T_ATTRIBUTE) { + $nextToken = $tokens[$nextToken]['attribute_closer']; + continue; + } + + break; + } while (true); + + $ignore = [ + T_CLASS => true, + T_INTERFACE => true, + T_TRAIT => true, + T_ENUM => true, + T_FUNCTION => true, + T_PUBLIC => true, + T_PRIVATE => true, + T_FINAL => true, + T_PROTECTED => true, + T_STATIC => true, + T_ABSTRACT => true, + T_CONST => true, + T_VAR => true, + T_READONLY => true, + ]; + if (isset($ignore[$tokens[$nextToken]['code']]) === true) { + return; + } + + $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prevToken]['code'] === T_OPEN_TAG) { + return; + } + + $error = 'Block comments must be started with /*'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'WrongStart'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, '/*'); + } + + $end = $tokens[$stackPtr]['comment_closer']; + if ($tokens[$end]['content'] !== '*/') { + $error = 'Block comments must be ended with */'; + $fix = $phpcsFile->addFixableError($error, $end, 'WrongEnd'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($end, '*/'); + } + } + + return; + }//end if + + $commentLines = [$stackPtr]; + $nextComment = $stackPtr; + $lastLine = $tokens[$stackPtr]['line']; + $commentString = $tokens[$stackPtr]['content']; + + // Construct the comment into an array. + while (($nextComment = $phpcsFile->findNext(T_WHITESPACE, ($nextComment + 1), null, true)) !== false) { + if ($tokens[$nextComment]['code'] !== $tokens[$stackPtr]['code'] + && isset(Tokens::$phpcsCommentTokens[$tokens[$nextComment]['code']]) === false + ) { + // Found the next bit of code. + break; + } + + if (($tokens[$nextComment]['line'] - 1) !== $lastLine) { + // Not part of the block. + break; + } + + $lastLine = $tokens[$nextComment]['line']; + $commentLines[] = $nextComment; + $commentString .= $tokens[$nextComment]['content']; + if ($tokens[$nextComment]['code'] === T_DOC_COMMENT_CLOSE_TAG + || substr($tokens[$nextComment]['content'], -2) === '*/' + ) { + break; + } + }//end while + + $commentText = str_replace($phpcsFile->eolChar, '', $commentString); + $commentText = trim($commentText, "/* \t"); + if ($commentText === '') { + $error = 'Empty block comment not allowed'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Empty'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($stackPtr, ''); + $lastToken = array_pop($commentLines); + for ($i = ($stackPtr + 1); $i <= $lastToken; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + } + + if (count($commentLines) === 1) { + $error = 'Single line block comment not allowed; use inline ("// text") comment instead'; + + // Only fix comments when they are the last token on a line. + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SingleLine'); + if ($fix === true) { + $comment = '// '.$commentText.$phpcsFile->eolChar; + $phpcsFile->fixer->replaceToken($stackPtr, $comment); + } + } else { + $phpcsFile->addError($error, $stackPtr, 'SingleLine'); + } + + return; + } + + $content = trim($tokens[$stackPtr]['content']); + if ($content !== '/*' && $content !== '/**') { + $error = 'Block comment text must start on a new line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoNewLine'); + if ($fix === true) { + $indent = ''; + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + if (isset($tokens[($stackPtr - 1)]['orig_content']) === true) { + $indent = $tokens[($stackPtr - 1)]['orig_content']; + } else { + $indent = $tokens[($stackPtr - 1)]['content']; + } + } + + $comment = preg_replace( + '/^(\s*\/\*\*?)/', + '$1'.$phpcsFile->eolChar.$indent, + $tokens[$stackPtr]['content'], + 1 + ); + $phpcsFile->fixer->replaceToken($stackPtr, $comment); + } + + return; + }//end if + + $starColumn = $tokens[$stackPtr]['column']; + $hasStars = false; + + // Make sure first line isn't blank. + if (trim($tokens[$commentLines[1]]['content']) === '') { + $error = 'Empty line not allowed at start of comment'; + $fix = $phpcsFile->addFixableError($error, $commentLines[1], 'HasEmptyLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($commentLines[1], ''); + } + } else { + // Check indentation of first line. + $content = $tokens[$commentLines[1]]['content']; + $commentText = ltrim($content); + $leadingSpace = (strlen($content) - strlen($commentText)); + + $expected = ($starColumn + 3); + if ($commentText[0] === '*') { + $expected = $starColumn; + $hasStars = true; + } + + if ($leadingSpace !== $expected) { + $expectedTxt = $expected.' space'; + if ($expected !== 1) { + $expectedTxt .= 's'; + } + + $data = [ + $expectedTxt, + $leadingSpace, + ]; + + $error = 'First line of comment not aligned correctly; expected %s but found %s'; + $fix = $phpcsFile->addFixableError($error, $commentLines[1], 'FirstLineIndent', $data); + if ($fix === true) { + if (isset($tokens[$commentLines[1]]['orig_content']) === true + && $tokens[$commentLines[1]]['orig_content'][0] === "\t" + ) { + // Line is indented using tabs. + $padding = str_repeat("\t", floor($expected / $this->tabWidth)); + $padding .= str_repeat(' ', ($expected % $this->tabWidth)); + } else { + $padding = str_repeat(' ', $expected); + } + + $phpcsFile->fixer->replaceToken($commentLines[1], $padding.$commentText); + } + }//end if + + if (preg_match('/^\p{Ll}/u', $commentText) === 1) { + $error = 'Block comments must start with a capital letter'; + $phpcsFile->addError($error, $commentLines[1], 'NoCapital'); + } + }//end if + + // Check that each line of the comment is indented past the star. + foreach ($commentLines as $line) { + // First and last lines (comment opener and closer) are handled separately. + if ($line === $commentLines[(count($commentLines) - 1)] || $line === $commentLines[0]) { + continue; + } + + // First comment line was handled above. + if ($line === $commentLines[1]) { + continue; + } + + // If it's empty, continue. + if (trim($tokens[$line]['content']) === '') { + continue; + } + + $commentText = ltrim($tokens[$line]['content']); + $leadingSpace = (strlen($tokens[$line]['content']) - strlen($commentText)); + + $expected = ($starColumn + 3); + if ($commentText[0] === '*') { + $expected = $starColumn; + $hasStars = true; + } + + if ($leadingSpace < $expected) { + $expectedTxt = $expected.' space'; + if ($expected !== 1) { + $expectedTxt .= 's'; + } + + $data = [ + $expectedTxt, + $leadingSpace, + ]; + + $error = 'Comment line indented incorrectly; expected at least %s but found %s'; + $fix = $phpcsFile->addFixableError($error, $line, 'LineIndent', $data); + if ($fix === true) { + if (isset($tokens[$line]['orig_content']) === true + && $tokens[$line]['orig_content'][0] === "\t" + ) { + // Line is indented using tabs. + $padding = str_repeat("\t", floor($expected / $this->tabWidth)); + $padding .= str_repeat(' ', ($expected % $this->tabWidth)); + } else { + $padding = str_repeat(' ', $expected); + } + + $phpcsFile->fixer->replaceToken($line, $padding.$commentText); + } + }//end if + }//end foreach + + // Finally, test the last line is correct. + $lastIndex = (count($commentLines) - 1); + $content = $tokens[$commentLines[$lastIndex]]['content']; + $commentText = ltrim($content); + if ($commentText !== '*/' && $commentText !== '**/') { + $error = 'Comment closer must be on a new line'; + $phpcsFile->addError($error, $commentLines[$lastIndex], 'CloserSameLine'); + } else { + $leadingSpace = (strlen($content) - strlen($commentText)); + + $expected = ($starColumn - 1); + if ($hasStars === true) { + $expected = $starColumn; + } + + if ($leadingSpace !== $expected) { + $expectedTxt = $expected.' space'; + if ($expected !== 1) { + $expectedTxt .= 's'; + } + + $data = [ + $expectedTxt, + $leadingSpace, + ]; + + $error = 'Last line of comment aligned incorrectly; expected %s but found %s'; + $fix = $phpcsFile->addFixableError($error, $commentLines[$lastIndex], 'LastLineIndent', $data); + if ($fix === true) { + if (isset($tokens[$line]['orig_content']) === true + && $tokens[$line]['orig_content'][0] === "\t" + ) { + // Line is indented using tabs. + $padding = str_repeat("\t", floor($expected / $this->tabWidth)); + $padding .= str_repeat(' ', ($expected % $this->tabWidth)); + } else { + $padding = str_repeat(' ', $expected); + } + + $phpcsFile->fixer->replaceToken($commentLines[$lastIndex], $padding.$commentText); + } + }//end if + }//end if + + // Check that the lines before and after this comment are blank. + $contentBefore = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ((isset($tokens[$contentBefore]['scope_closer']) === true + && $tokens[$contentBefore]['scope_opener'] === $contentBefore) + || $tokens[$contentBefore]['code'] === T_OPEN_TAG + || $tokens[$contentBefore]['code'] === T_OPEN_TAG_WITH_ECHO + ) { + if (($tokens[$stackPtr]['line'] - $tokens[$contentBefore]['line']) !== 1) { + $error = 'Empty line not required before block comment'; + $phpcsFile->addError($error, $stackPtr, 'HasEmptyLineBefore'); + } + } else { + if (($tokens[$stackPtr]['line'] - $tokens[$contentBefore]['line']) < 2) { + $error = 'Empty line required before block comment'; + $phpcsFile->addError($error, $stackPtr, 'NoEmptyLineBefore'); + } + } + + $commentCloser = $commentLines[$lastIndex]; + $contentAfter = $phpcsFile->findNext(T_WHITESPACE, ($commentCloser + 1), null, true); + if ($contentAfter !== false && ($tokens[$contentAfter]['line'] - $tokens[$commentCloser]['line']) < 2) { + $error = 'Empty line required after block comment'; + $phpcsFile->addError($error, $commentCloser, 'NoEmptyLineAfter'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClassCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClassCommentSniff.php new file mode 100644 index 0000000..60d553f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClassCommentSniff.php @@ -0,0 +1,109 @@ + + *
  • A class doc comment exists.
  • + *
  • The comment uses the correct docblock style.
  • + *
  • There are no blank lines after the class comment.
  • + *
  • No tags are used in the docblock.
  • + * + * + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClassCommentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLASS]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $find = [ + T_ABSTRACT => T_ABSTRACT, + T_FINAL => T_FINAL, + T_READONLY => T_READONLY, + T_WHITESPACE => T_WHITESPACE, + ]; + + $previousContent = null; + for ($commentEnd = ($stackPtr - 1); $commentEnd >= 0; $commentEnd--) { + if (isset($find[$tokens[$commentEnd]['code']]) === true) { + continue; + } + + if ($previousContent === null) { + $previousContent = $commentEnd; + } + + if ($tokens[$commentEnd]['code'] === T_ATTRIBUTE_END + && isset($tokens[$commentEnd]['attribute_opener']) === true + ) { + $commentEnd = $tokens[$commentEnd]['attribute_opener']; + continue; + } + + break; + } + + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT + ) { + $class = $phpcsFile->getDeclarationName($stackPtr); + $phpcsFile->addError('Missing doc comment for class %s', $stackPtr, 'Missing', [$class]); + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'no'); + return; + } + + $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'yes'); + + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle'); + return; + } + + if ($tokens[$previousContent]['line'] !== ($tokens[$stackPtr]['line'] - 1)) { + $error = 'There must be no blank lines after the class comment'; + $phpcsFile->addError($error, $commentEnd, 'SpacingAfter'); + } + + $commentStart = $tokens[$commentEnd]['comment_opener']; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + $error = '%s tag is not allowed in class comment'; + $data = [$tokens[$tag]['content']]; + $phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php new file mode 100644 index 0000000..45bcdbd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php @@ -0,0 +1,132 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ClosingDeclarationCommentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLASS, + T_INTERFACE, + T_ENUM, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens.. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_FUNCTION) { + $methodProps = $phpcsFile->getMethodProperties($stackPtr); + + // Abstract methods do not require a closing comment. + if ($methodProps['is_abstract'] === true) { + return; + } + + // If this function is in an interface then we don't require + // a closing comment. + if ($phpcsFile->hasCondition($stackPtr, T_INTERFACE) === true) { + return; + } + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + $error = 'Possible parse error: non-abstract method defined as abstract'; + $phpcsFile->addWarning($error, $stackPtr, 'Abstract'); + return; + } + + $decName = $phpcsFile->getDeclarationName($stackPtr); + $comment = '//end '.$decName.'()'; + } else if ($tokens[$stackPtr]['code'] === T_CLASS) { + $comment = '//end class'; + } else if ($tokens[$stackPtr]['code'] === T_INTERFACE) { + $comment = '//end interface'; + } else { + $comment = '//end enum'; + }//end if + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $data); + return; + } + + $closingBracket = $tokens[$stackPtr]['scope_closer']; + + if ($closingBracket === null) { + // Possible inline structure. Other tests will handle it. + return; + } + + $data = [$comment]; + if (isset($tokens[($closingBracket + 1)]) === false || $tokens[($closingBracket + 1)]['code'] !== T_COMMENT) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($closingBracket + 1), null, true); + if (rtrim($tokens[$next]['content']) === $comment) { + // The comment isn't really missing; it is just in the wrong place. + $fix = $phpcsFile->addFixableError('Expected %s directly after closing brace', $closingBracket, 'Misplaced', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($closingBracket + 1); $i < $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + // Just in case, because indentation fixes can add indents onto + // these comments and cause us to be unable to fix them. + $phpcsFile->fixer->replaceToken($next, $comment.$phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } else { + $fix = $phpcsFile->addFixableError('Expected %s', $closingBracket, 'Missing', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($closingBracket, '}'.$comment.$phpcsFile->eolChar); + } + } + + return; + }//end if + + if (rtrim($tokens[($closingBracket + 1)]['content']) !== $comment) { + $fix = $phpcsFile->addFixableError('Expected %s', $closingBracket, 'Incorrect', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($closingBracket + 1), $comment.$phpcsFile->eolChar); + } + + return; + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php new file mode 100644 index 0000000..453ff89 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php @@ -0,0 +1,167 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DocCommentAlignmentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_DOC_COMMENT_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // We are only interested in function/class/interface doc block comments. + $ignore = Tokens::$emptyTokens; + if ($phpcsFile->tokenizerType === 'JS') { + $ignore[] = T_EQUAL; + $ignore[] = T_STRING; + $ignore[] = T_OBJECT_OPERATOR; + } + + $nextToken = $phpcsFile->findNext($ignore, ($stackPtr + 1), null, true); + $ignore = [ + T_CLASS => true, + T_INTERFACE => true, + T_ENUM => true, + T_ENUM_CASE => true, + T_FUNCTION => true, + T_PUBLIC => true, + T_PRIVATE => true, + T_PROTECTED => true, + T_STATIC => true, + T_ABSTRACT => true, + T_PROPERTY => true, + T_OBJECT => true, + T_PROTOTYPE => true, + T_VAR => true, + T_READONLY => true, + ]; + + if ($nextToken === false || isset($ignore[$tokens[$nextToken]['code']]) === false) { + // Could be a file comment. + $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prevToken]['code'] !== T_OPEN_TAG) { + return; + } + } + + // There must be one space after each star (unless it is an empty comment line) + // and all the stars must be aligned correctly. + $requiredColumn = ($tokens[$stackPtr]['column'] + 1); + $endComment = $tokens[$stackPtr]['comment_closer']; + for ($i = ($stackPtr + 1); $i <= $endComment; $i++) { + if ($tokens[$i]['code'] !== T_DOC_COMMENT_STAR + && $tokens[$i]['code'] !== T_DOC_COMMENT_CLOSE_TAG + ) { + continue; + } + + if ($tokens[$i]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + if (trim($tokens[$i]['content']) === '') { + // Don't process an unfinished docblock close tag during live coding. + continue; + } + + // Can't process the close tag if it is not the first thing on the line. + $prev = $phpcsFile->findPrevious(T_DOC_COMMENT_WHITESPACE, ($i - 1), $stackPtr, true); + if ($tokens[$prev]['line'] === $tokens[$i]['line']) { + continue; + } + } + + if ($tokens[$i]['column'] !== $requiredColumn) { + $pluralizeSpace = 's'; + if (($requiredColumn - 1) === 1) { + $pluralizeSpace = ''; + } + + $error = 'Expected %s space%s before asterisk; %s found'; + $data = [ + ($requiredColumn - 1), + $pluralizeSpace, + ($tokens[$i]['column'] - 1), + ]; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceBeforeStar', $data); + if ($fix === true) { + $padding = str_repeat(' ', ($requiredColumn - 1)); + if ($tokens[$i]['column'] === 1) { + $phpcsFile->fixer->addContentBefore($i, $padding); + } else { + $phpcsFile->fixer->replaceToken(($i - 1), $padding); + } + } + }//end if + + if ($tokens[$i]['code'] !== T_DOC_COMMENT_STAR) { + continue; + } + + if ($tokens[($i + 2)]['line'] !== $tokens[$i]['line']) { + // Line is empty. + continue; + } + + if ($tokens[($i + 1)]['code'] !== T_DOC_COMMENT_WHITESPACE) { + $error = 'Expected 1 space after asterisk; 0 found'; + $fix = $phpcsFile->addFixableError($error, $i, 'NoSpaceAfterStar'); + if ($fix === true) { + $phpcsFile->fixer->addContent($i, ' '); + } + } else if ($tokens[($i + 2)]['code'] === T_DOC_COMMENT_TAG + && $tokens[($i + 1)]['content'] !== ' ' + ) { + $error = 'Expected 1 space after asterisk; %s found'; + $data = [$tokens[($i + 1)]['length']]; + $fix = $phpcsFile->addFixableError($error, $i, 'SpaceAfterStar', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($i + 1), ' '); + } + } + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/EmptyCatchCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/EmptyCatchCommentSniff.php new file mode 100644 index 0000000..301537f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/EmptyCatchCommentSniff.php @@ -0,0 +1,55 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class EmptyCatchCommentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CATCH]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile All the tokens found in the document. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $scopeStart = $tokens[$stackPtr]['scope_opener']; + $firstContent = $phpcsFile->findNext(T_WHITESPACE, ($scopeStart + 1), $tokens[$stackPtr]['scope_closer'], true); + + if ($firstContent === false) { + $error = 'Empty CATCH statement must have a comment to explain why the exception is not handled'; + $phpcsFile->addError($error, $scopeStart, 'Missing'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php new file mode 100644 index 0000000..d9241f1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php @@ -0,0 +1,228 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FileCommentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + + if ($tokens[$commentStart]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a file comment', $commentStart, 'WrongStyle'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + return ($phpcsFile->numTokens + 1); + } else if ($commentStart === false || $tokens[$commentStart]['code'] !== T_DOC_COMMENT_OPEN_TAG) { + $phpcsFile->addError('Missing file doc comment', $stackPtr, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); + return ($phpcsFile->numTokens + 1); + } + + if (isset($tokens[$commentStart]['comment_closer']) === false + || ($tokens[$tokens[$commentStart]['comment_closer']]['content'] === '' + && $tokens[$commentStart]['comment_closer'] === ($phpcsFile->numTokens - 1)) + ) { + // Don't process an unfinished file comment during live coding. + return ($phpcsFile->numTokens + 1); + } + + $commentEnd = $tokens[$commentStart]['comment_closer']; + + for ($nextToken = ($commentEnd + 1); $nextToken < $phpcsFile->numTokens; $nextToken++) { + if ($tokens[$nextToken]['code'] === T_WHITESPACE) { + continue; + } + + if ($tokens[$nextToken]['code'] === T_ATTRIBUTE + && isset($tokens[$nextToken]['attribute_closer']) === true + ) { + $nextToken = $tokens[$nextToken]['attribute_closer']; + continue; + } + + break; + } + + if ($nextToken === $phpcsFile->numTokens) { + $nextToken--; + } + + $ignore = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + T_CLOSURE, + T_PUBLIC, + T_PRIVATE, + T_PROTECTED, + T_FINAL, + T_STATIC, + T_ABSTRACT, + T_READONLY, + T_CONST, + T_PROPERTY, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + ]; + + if (in_array($tokens[$nextToken]['code'], $ignore, true) === true) { + $phpcsFile->addError('Missing file doc comment', $stackPtr, 'Missing'); + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); + return ($phpcsFile->numTokens + 1); + } + + $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); + + // No blank line between the open tag and the file comment. + if ($tokens[$commentStart]['line'] > ($tokens[$stackPtr]['line'] + 1)) { + $error = 'There must be no blank lines before the file comment'; + $phpcsFile->addError($error, $stackPtr, 'SpacingAfterOpen'); + } + + // Exactly one blank line after the file comment. + $next = $phpcsFile->findNext(T_WHITESPACE, ($commentEnd + 1), null, true); + if ($next !== false && $tokens[$next]['line'] !== ($tokens[$commentEnd]['line'] + 2)) { + $error = 'There must be exactly one blank line after the file comment'; + $phpcsFile->addError($error, $commentEnd, 'SpacingAfterComment'); + } + + // Required tags in correct order. + $required = [ + '@package' => true, + '@subpackage' => true, + '@author' => true, + '@copyright' => true, + ]; + + $foundTags = []; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + $name = $tokens[$tag]['content']; + $isRequired = isset($required[$name]); + + if ($isRequired === true && in_array($name, $foundTags, true) === true) { + $error = 'Only one %s tag is allowed in a file comment'; + $data = [$name]; + $phpcsFile->addError($error, $tag, 'Duplicate'.ucfirst(substr($name, 1)).'Tag', $data); + } + + $foundTags[] = $name; + + if ($isRequired === false) { + continue; + } + + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for %s tag in file comment'; + $data = [$name]; + $phpcsFile->addError($error, $tag, 'Empty'.ucfirst(substr($name, 1)).'Tag', $data); + continue; + } + + if ($name === '@author') { + if ($tokens[$string]['content'] !== 'Squiz Pty Ltd ') { + $error = 'Expected "Squiz Pty Ltd " for author tag'; + $fix = $phpcsFile->addFixableError($error, $tag, 'IncorrectAuthor'); + if ($fix === true) { + $expected = 'Squiz Pty Ltd '; + $phpcsFile->fixer->replaceToken($string, $expected); + } + } + } else if ($name === '@copyright') { + if (preg_match('/^([0-9]{4})(-[0-9]{4})? (Squiz Pty Ltd \(ABN 77 084 670 600\))$/', $tokens[$string]['content']) === 0) { + $error = 'Expected "xxxx-xxxx Squiz Pty Ltd (ABN 77 084 670 600)" for copyright declaration'; + $fix = $phpcsFile->addFixableError($error, $tag, 'IncorrectCopyright'); + if ($fix === true) { + $matches = []; + preg_match('/^(([0-9]{4})(-[0-9]{4})?)?.*$/', $tokens[$string]['content'], $matches); + if (isset($matches[1]) === false) { + $matches[1] = date('Y'); + } + + $expected = $matches[1].' Squiz Pty Ltd (ABN 77 084 670 600)'; + $phpcsFile->fixer->replaceToken($string, $expected); + } + } + }//end if + }//end foreach + + // Check if the tags are in the correct position. + $pos = 0; + foreach ($required as $tag => $true) { + if (in_array($tag, $foundTags, true) === false) { + $error = 'Missing %s tag in file comment'; + $data = [$tag]; + $phpcsFile->addError($error, $commentEnd, 'Missing'.ucfirst(substr($tag, 1)).'Tag', $data); + } + + if (isset($foundTags[$pos]) === false) { + break; + } + + if ($foundTags[$pos] !== $tag) { + $error = 'The tag in position %s should be the %s tag'; + $data = [ + ($pos + 1), + $tag, + ]; + $phpcsFile->addError($error, $tokens[$commentStart]['comment_tags'][$pos], ucfirst(substr($tag, 1)).'TagOrder', $data); + } + + $pos++; + }//end foreach + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php new file mode 100644 index 0000000..644fd50 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php @@ -0,0 +1,797 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FunctionCommentSniff as PEARFunctionCommentSniff; +use PHP_CodeSniffer\Util\Common; + +class FunctionCommentSniff extends PEARFunctionCommentSniff +{ + + /** + * Whether to skip inheritdoc comments. + * + * @var boolean + */ + public $skipIfInheritdoc = false; + + /** + * The current PHP version. + * + * @var integer|string|null + */ + private $phpVersion = null; + + + /** + * Process the return comment of this function comment. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processReturn(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + $return = null; + + if ($this->skipIfInheritdoc === true) { + if ($this->checkInheritdoc($phpcsFile, $stackPtr, $commentStart) === true) { + return; + } + } + + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@return') { + if ($return !== null) { + $error = 'Only 1 @return tag is allowed in a function comment'; + $phpcsFile->addError($error, $tag, 'DuplicateReturn'); + return; + } + + $return = $tag; + } + } + + // Skip constructor and destructor. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + $isSpecialMethod = in_array($methodName, $this->specialMethods, true); + + if ($return !== null) { + $content = $tokens[($return + 2)]['content']; + if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) { + $error = 'Return type missing for @return tag in function comment'; + $phpcsFile->addError($error, $return, 'MissingReturnType'); + } else { + // Support both a return type and a description. + preg_match('`^((?:\|?(?:array\([^\)]*\)|[\\\\a-z0-9\[\]]+))*)( .*)?`i', $content, $returnParts); + if (isset($returnParts[1]) === false) { + return; + } + + $returnType = $returnParts[1]; + + // Check return type (can be multiple, separated by '|'). + $typeNames = explode('|', $returnType); + $suggestedNames = []; + foreach ($typeNames as $i => $typeName) { + $suggestedName = Common::suggestType($typeName); + if (in_array($suggestedName, $suggestedNames, true) === false) { + $suggestedNames[] = $suggestedName; + } + } + + $suggestedType = implode('|', $suggestedNames); + if ($returnType !== $suggestedType) { + $error = 'Expected "%s" but found "%s" for function return type'; + $data = [ + $suggestedType, + $returnType, + ]; + $fix = $phpcsFile->addFixableError($error, $return, 'InvalidReturn', $data); + if ($fix === true) { + $replacement = $suggestedType; + if (empty($returnParts[2]) === false) { + $replacement .= $returnParts[2]; + } + + $phpcsFile->fixer->replaceToken(($return + 2), $replacement); + unset($replacement); + } + } + + // If the return type is void, make sure there is + // no return statement in the function. + if ($returnType === 'void') { + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $endToken = $tokens[$stackPtr]['scope_closer']; + for ($returnToken = $stackPtr; $returnToken < $endToken; $returnToken++) { + if ($tokens[$returnToken]['code'] === T_CLOSURE + || $tokens[$returnToken]['code'] === T_ANON_CLASS + ) { + $returnToken = $tokens[$returnToken]['scope_closer']; + continue; + } + + if ($tokens[$returnToken]['code'] === T_RETURN + || $tokens[$returnToken]['code'] === T_YIELD + || $tokens[$returnToken]['code'] === T_YIELD_FROM + ) { + break; + } + } + + if ($returnToken !== $endToken) { + // If the function is not returning anything, just + // exiting, then there is no problem. + $semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true); + if ($tokens[$semicolon]['code'] !== T_SEMICOLON) { + $error = 'Function return type is void, but function contains return statement'; + $phpcsFile->addError($error, $return, 'InvalidReturnVoid'); + } + } + }//end if + } else if ($returnType !== 'mixed' + && $returnType !== 'never' + && in_array('void', $typeNames, true) === false + ) { + // If return type is not void, never, or mixed, there needs to be a + // return statement somewhere in the function that returns something. + if (isset($tokens[$stackPtr]['scope_closer']) === true) { + $endToken = $tokens[$stackPtr]['scope_closer']; + for ($returnToken = $stackPtr; $returnToken < $endToken; $returnToken++) { + if ($tokens[$returnToken]['code'] === T_CLOSURE + || $tokens[$returnToken]['code'] === T_ANON_CLASS + ) { + $returnToken = $tokens[$returnToken]['scope_closer']; + continue; + } + + if ($tokens[$returnToken]['code'] === T_RETURN + || $tokens[$returnToken]['code'] === T_YIELD + || $tokens[$returnToken]['code'] === T_YIELD_FROM + ) { + break; + } + } + + if ($returnToken === $endToken) { + $error = 'Function return type is not void, but function has no return statement'; + $phpcsFile->addError($error, $return, 'InvalidNoReturn'); + } else { + $semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true); + if ($tokens[$semicolon]['code'] === T_SEMICOLON) { + $error = 'Function return type is not void, but function is returning void here'; + $phpcsFile->addError($error, $returnToken, 'InvalidReturnNotVoid'); + } + } + }//end if + }//end if + }//end if + } else { + if ($isSpecialMethod === true) { + return; + } + + $error = 'Missing @return tag in function comment'; + $phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn'); + }//end if + + }//end processReturn() + + + /** + * Process any throw tags that this function comment has. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processThrows(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + if ($this->skipIfInheritdoc === true) { + if ($this->checkInheritdoc($phpcsFile, $stackPtr, $commentStart) === true) { + return; + } + } + + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($tokens[$tag]['content'] !== '@throws') { + continue; + } + + $exception = null; + $comment = null; + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = []; + preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches); + $exception = $matches[1]; + if (isset($matches[2]) === true && trim($matches[2]) !== '') { + $comment = $matches[2]; + } + } + + if ($exception === null) { + $error = 'Exception type and comment missing for @throws tag in function comment'; + $phpcsFile->addError($error, $tag, 'InvalidThrows'); + } else if ($comment === null) { + $error = 'Comment missing for @throws tag in function comment'; + $phpcsFile->addError($error, $tag, 'EmptyThrows'); + } else { + // Any strings until the next tag belong to this comment. + if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) { + $end = $tokens[$commentStart]['comment_tags'][($pos + 1)]; + } else { + $end = $tokens[$commentStart]['comment_closer']; + } + + for ($i = ($tag + 3); $i < $end; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) { + $comment .= ' '.$tokens[$i]['content']; + } + } + + $comment = trim($comment); + + // Starts with a capital letter and ends with a fullstop. + $firstChar = $comment[0]; + if (strtoupper($firstChar) !== $firstChar) { + $error = '@throws tag comment must start with a capital letter'; + $phpcsFile->addError($error, ($tag + 2), 'ThrowsNotCapital'); + } + + $lastChar = substr($comment, -1); + if ($lastChar !== '.') { + $error = '@throws tag comment must end with a full stop'; + $phpcsFile->addError($error, ($tag + 2), 'ThrowsNoFullStop'); + } + }//end if + }//end foreach + + }//end processThrows() + + + /** + * Process the function parameter comments. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return void + */ + protected function processParams(File $phpcsFile, $stackPtr, $commentStart) + { + if ($this->phpVersion === null) { + $this->phpVersion = Config::getConfigData('php_version'); + if ($this->phpVersion === null) { + $this->phpVersion = PHP_VERSION_ID; + } + } + + $tokens = $phpcsFile->getTokens(); + + if ($this->skipIfInheritdoc === true) { + if ($this->checkInheritdoc($phpcsFile, $stackPtr, $commentStart) === true) { + return; + } + } + + $params = []; + $maxType = 0; + $maxVar = 0; + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($tokens[$tag]['content'] !== '@param') { + continue; + } + + $type = ''; + $typeSpace = 0; + $var = ''; + $varSpace = 0; + $comment = ''; + $commentLines = []; + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $matches = []; + preg_match('/([^$&.]+)(?:((?:\.\.\.)?(?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches); + + if (empty($matches) === false) { + $typeLen = strlen($matches[1]); + $type = trim($matches[1]); + $typeSpace = ($typeLen - strlen($type)); + $typeLen = strlen($type); + if ($typeLen > $maxType) { + $maxType = $typeLen; + } + } + + if (isset($matches[2]) === true) { + $var = $matches[2]; + $varLen = strlen($var); + if ($varLen > $maxVar) { + $maxVar = $varLen; + } + + if (isset($matches[4]) === true) { + $varSpace = strlen($matches[3]); + $comment = $matches[4]; + $commentLines[] = [ + 'comment' => $comment, + 'token' => ($tag + 2), + 'indent' => $varSpace, + ]; + + // Any strings until the next tag belong to this comment. + if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) { + $end = $tokens[$commentStart]['comment_tags'][($pos + 1)]; + } else { + $end = $tokens[$commentStart]['comment_closer']; + } + + for ($i = ($tag + 3); $i < $end; $i++) { + if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) { + $indent = 0; + if ($tokens[($i - 1)]['code'] === T_DOC_COMMENT_WHITESPACE) { + $indent = $tokens[($i - 1)]['length']; + } + + $comment .= ' '.$tokens[$i]['content']; + $commentLines[] = [ + 'comment' => $tokens[$i]['content'], + 'token' => $i, + 'indent' => $indent, + ]; + } + } + } else { + $error = 'Missing parameter comment'; + $phpcsFile->addError($error, $tag, 'MissingParamComment'); + $commentLines[] = ['comment' => '']; + }//end if + } else { + $error = 'Missing parameter name'; + $phpcsFile->addError($error, $tag, 'MissingParamName'); + }//end if + } else { + $error = 'Missing parameter type'; + $phpcsFile->addError($error, $tag, 'MissingParamType'); + }//end if + + $params[] = [ + 'tag' => $tag, + 'type' => $type, + 'var' => $var, + 'comment' => $comment, + 'commentLines' => $commentLines, + 'type_space' => $typeSpace, + 'var_space' => $varSpace, + ]; + }//end foreach + + $realParams = $phpcsFile->getMethodParameters($stackPtr); + $foundParams = []; + + // We want to use ... for all variable length arguments, so added + // this prefix to the variable name so comparisons are easier. + foreach ($realParams as $pos => $param) { + if ($param['variable_length'] === true) { + $realParams[$pos]['name'] = '...'.$realParams[$pos]['name']; + } + } + + foreach ($params as $pos => $param) { + // If the type is empty, the whole line is empty. + if ($param['type'] === '') { + continue; + } + + // Check the param type value. + $typeNames = explode('|', $param['type']); + $suggestedTypeNames = []; + + foreach ($typeNames as $typeName) { + if ($typeName === '') { + continue; + } + + // Strip nullable operator. + if ($typeName[0] === '?') { + $typeName = substr($typeName, 1); + } + + $suggestedName = Common::suggestType($typeName); + $suggestedTypeNames[] = $suggestedName; + + if (count($typeNames) > 1) { + continue; + } + + // Check type hint for array and custom type. + $suggestedTypeHint = ''; + if (strpos($suggestedName, 'array') !== false || substr($suggestedName, -2) === '[]') { + $suggestedTypeHint = 'array'; + } else if (strpos($suggestedName, 'callable') !== false) { + $suggestedTypeHint = 'callable'; + } else if (strpos($suggestedName, 'callback') !== false) { + $suggestedTypeHint = 'callable'; + } else if (in_array($suggestedName, Common::$allowedTypes, true) === false) { + $suggestedTypeHint = $suggestedName; + } + + if ($this->phpVersion >= 70000) { + if ($suggestedName === 'string') { + $suggestedTypeHint = 'string'; + } else if ($suggestedName === 'int' || $suggestedName === 'integer') { + $suggestedTypeHint = 'int'; + } else if ($suggestedName === 'float') { + $suggestedTypeHint = 'float'; + } else if ($suggestedName === 'bool' || $suggestedName === 'boolean') { + $suggestedTypeHint = 'bool'; + } + } + + if ($this->phpVersion >= 70200) { + if ($suggestedName === 'object') { + $suggestedTypeHint = 'object'; + } + } + + if ($this->phpVersion >= 80000) { + if ($suggestedName === 'mixed') { + $suggestedTypeHint = 'mixed'; + } + } + + if ($suggestedTypeHint !== '' && isset($realParams[$pos]) === true) { + $typeHint = $realParams[$pos]['type_hint']; + + // Remove namespace prefixes when comparing. + $compareTypeHint = substr($suggestedTypeHint, (strlen($typeHint) * -1)); + + if ($typeHint === '') { + $error = 'Type hint "%s" missing for %s'; + $data = [ + $suggestedTypeHint, + $param['var'], + ]; + + $errorCode = 'TypeHintMissing'; + if ($suggestedTypeHint === 'string' + || $suggestedTypeHint === 'int' + || $suggestedTypeHint === 'float' + || $suggestedTypeHint === 'bool' + ) { + $errorCode = 'Scalar'.$errorCode; + } + + $phpcsFile->addError($error, $stackPtr, $errorCode, $data); + } else if ($typeHint !== $compareTypeHint && $typeHint !== '?'.$compareTypeHint) { + $error = 'Expected type hint "%s"; found "%s" for %s'; + $data = [ + $suggestedTypeHint, + $typeHint, + $param['var'], + ]; + $phpcsFile->addError($error, $stackPtr, 'IncorrectTypeHint', $data); + }//end if + } else if ($suggestedTypeHint === '' && isset($realParams[$pos]) === true) { + $typeHint = $realParams[$pos]['type_hint']; + if ($typeHint !== '') { + $error = 'Unknown type hint "%s" found for %s'; + $data = [ + $typeHint, + $param['var'], + ]; + $phpcsFile->addError($error, $stackPtr, 'InvalidTypeHint', $data); + } + }//end if + }//end foreach + + $suggestedType = implode('|', $suggestedTypeNames); + if ($param['type'] !== $suggestedType) { + $error = 'Expected "%s" but found "%s" for parameter type'; + $data = [ + $suggestedType, + $param['type'], + ]; + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'IncorrectParamVarName', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + $content = $suggestedType; + $content .= str_repeat(' ', $param['type_space']); + $content .= $param['var']; + $content .= str_repeat(' ', $param['var_space']); + if (isset($param['commentLines'][0]) === true) { + $content .= $param['commentLines'][0]['comment']; + } + + $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); + + // Fix up the indent of additional comment lines. + foreach ($param['commentLines'] as $lineNum => $line) { + if ($lineNum === 0 + || $param['commentLines'][$lineNum]['indent'] === 0 + ) { + continue; + } + + $diff = (strlen($param['type']) - strlen($suggestedType)); + $newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff); + $phpcsFile->fixer->replaceToken( + ($param['commentLines'][$lineNum]['token'] - 1), + str_repeat(' ', $newIndent) + ); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + + if ($param['var'] === '') { + continue; + } + + $foundParams[] = $param['var']; + + // Check number of spaces after the type. + $this->checkSpacingAfterParamType($phpcsFile, $param, $maxType); + + // Make sure the param name is correct. + if (isset($realParams[$pos]) === true) { + $realName = $realParams[$pos]['name']; + $paramVarName = $param['var']; + + if ($param['var'][0] === '&') { + // Even when passed by reference, the variable name in $realParams does not have + // a leading '&'. This sniff will accept both '&$var' and '$var' in these cases. + $paramVarName = substr($param['var'], 1); + + // This makes sure that the 'MissingParamTag' check won't throw a false positive. + $foundParams[(count($foundParams) - 1)] = $paramVarName; + + if ($realParams[$pos]['pass_by_reference'] !== true && $realName === $paramVarName) { + // Don't complain about this unless the param name is otherwise correct. + $error = 'Doc comment for parameter %s is prefixed with "&" but parameter is not passed by reference'; + $code = 'ParamNameUnexpectedAmpersandPrefix'; + $data = [$paramVarName]; + + // We're not offering an auto-fix here because we can't tell if the docblock + // is wrong, or the parameter should be passed by reference. + $phpcsFile->addError($error, $param['tag'], $code, $data); + } + } + + if ($realName !== $paramVarName) { + $code = 'ParamNameNoMatch'; + $data = [ + $paramVarName, + $realName, + ]; + + $error = 'Doc comment for parameter %s does not match '; + if (strtolower($paramVarName) === strtolower($realName)) { + $error .= 'case of '; + $code = 'ParamNameNoCaseMatch'; + } + + $error .= 'actual variable name %s'; + + $phpcsFile->addError($error, $param['tag'], $code, $data); + }//end if + } else if (substr($param['var'], -4) !== ',...') { + // We must have an extra parameter comment. + $error = 'Superfluous parameter comment'; + $phpcsFile->addError($error, $param['tag'], 'ExtraParamComment'); + }//end if + + if ($param['comment'] === '') { + continue; + } + + // Check number of spaces after the var name. + $this->checkSpacingAfterParamName($phpcsFile, $param, $maxVar); + + // Param comments must start with a capital letter and end with a full stop. + if (preg_match('/^(\p{Ll}|\P{L})/u', $param['comment']) === 1) { + $error = 'Parameter comment must start with a capital letter'; + $phpcsFile->addError($error, $param['tag'], 'ParamCommentNotCapital'); + } + + $lastChar = substr($param['comment'], -1); + if ($lastChar !== '.') { + $error = 'Parameter comment must end with a full stop'; + $phpcsFile->addError($error, $param['tag'], 'ParamCommentFullStop'); + } + }//end foreach + + $realNames = []; + foreach ($realParams as $realParam) { + $realNames[] = $realParam['name']; + } + + // Report missing comments. + $diff = array_diff($realNames, $foundParams); + foreach ($diff as $neededParam) { + $error = 'Doc comment for parameter "%s" missing'; + $data = [$neededParam]; + $phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data); + } + + }//end processParams() + + + /** + * Check the spacing after the type of a parameter. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $param The parameter to be checked. + * @param int $maxType The maxlength of the longest parameter type. + * @param int $spacing The number of spaces to add after the type. + * + * @return void + */ + protected function checkSpacingAfterParamType(File $phpcsFile, $param, $maxType, $spacing=1) + { + // Check number of spaces after the type. + $spaces = ($maxType - strlen($param['type']) + $spacing); + if ($param['type_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter type; %s found'; + $data = [ + $spaces, + $param['type_space'], + ]; + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + $content = $param['type']; + $content .= str_repeat(' ', $spaces); + $content .= $param['var']; + $content .= str_repeat(' ', $param['var_space']); + $content .= $param['commentLines'][0]['comment']; + $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); + + // Fix up the indent of additional comment lines. + $diff = ($param['type_space'] - $spaces); + foreach ($param['commentLines'] as $lineNum => $line) { + if ($lineNum === 0 + || $param['commentLines'][$lineNum]['indent'] === 0 + ) { + continue; + } + + $newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff); + if ($newIndent <= 0) { + continue; + } + + $phpcsFile->fixer->replaceToken( + ($param['commentLines'][$lineNum]['token'] - 1), + str_repeat(' ', $newIndent) + ); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + + }//end checkSpacingAfterParamType() + + + /** + * Check the spacing after the name of a parameter. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $param The parameter to be checked. + * @param int $maxVar The maxlength of the longest parameter name. + * @param int $spacing The number of spaces to add after the type. + * + * @return void + */ + protected function checkSpacingAfterParamName(File $phpcsFile, $param, $maxVar, $spacing=1) + { + // Check number of spaces after the var name. + $spaces = ($maxVar - strlen($param['var']) + $spacing); + if ($param['var_space'] !== $spaces) { + $error = 'Expected %s spaces after parameter name; %s found'; + $data = [ + $spaces, + $param['var_space'], + ]; + + $fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamName', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + + $content = $param['type']; + $content .= str_repeat(' ', $param['type_space']); + $content .= $param['var']; + $content .= str_repeat(' ', $spaces); + $content .= $param['commentLines'][0]['comment']; + $phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content); + + // Fix up the indent of additional comment lines. + foreach ($param['commentLines'] as $lineNum => $line) { + if ($lineNum === 0 + || $param['commentLines'][$lineNum]['indent'] === 0 + ) { + continue; + } + + $diff = ($param['var_space'] - $spaces); + $newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff); + if ($newIndent <= 0) { + continue; + } + + $phpcsFile->fixer->replaceToken( + ($param['commentLines'][$lineNum]['token'] - 1), + str_repeat(' ', $newIndent) + ); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + + }//end checkSpacingAfterParamName() + + + /** + * Determines whether the whole comment is an inheritdoc comment. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $commentStart The position in the stack where the comment started. + * + * @return boolean TRUE if the docblock contains only {@inheritdoc} (case-insensitive). + */ + protected function checkInheritdoc(File $phpcsFile, $stackPtr, $commentStart) + { + $tokens = $phpcsFile->getTokens(); + + $allowedTokens = [ + T_DOC_COMMENT_OPEN_TAG, + T_DOC_COMMENT_WHITESPACE, + T_DOC_COMMENT_STAR, + ]; + for ($i = $commentStart; $i <= $tokens[$commentStart]['comment_closer']; $i++) { + if (in_array($tokens[$i]['code'], $allowedTokens) === false) { + $trimmedContent = strtolower(trim($tokens[$i]['content'])); + + if ($trimmedContent === '{@inheritdoc}') { + return true; + } else { + return false; + } + } + } + + return false; + + }//end checkInheritdoc() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php new file mode 100644 index 0000000..4fb332c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php @@ -0,0 +1,233 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionCommentThrowTagSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + // Abstract or incomplete. + return; + } + + $find = Tokens::$methodPrefixes; + $find[] = T_WHITESPACE; + + $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); + if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG) { + // Function doesn't have a doc comment or is using the wrong type of comment. + return; + } + + $stackPtrEnd = $tokens[$stackPtr]['scope_closer']; + + // Find all the exception type tokens within the current scope. + $thrownExceptions = []; + $currPos = $stackPtr; + $foundThrows = false; + $unknownCount = 0; + do { + $currPos = $phpcsFile->findNext([T_THROW, T_ANON_CLASS, T_CLOSURE], ($currPos + 1), $stackPtrEnd); + if ($currPos === false) { + break; + } + + if ($tokens[$currPos]['code'] !== T_THROW) { + $currPos = $tokens[$currPos]['scope_closer']; + continue; + } + + $foundThrows = true; + + /* + If we can't find a NEW, we are probably throwing + a variable or calling a method. + + If we're throwing a variable, and it's the same variable as the + exception container from the nearest 'catch' block, we take that exception + as it is likely to be a re-throw. + + If we can't find a matching catch block, or the variable name + is different, it's probably a different variable, so we ignore it, + but they still need to provide at least one @throws tag, even through we + don't know the exception class. + */ + + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($currPos + 1), null, true); + if ($tokens[$nextToken]['code'] === T_NEW + || $tokens[$nextToken]['code'] === T_NS_SEPARATOR + || $tokens[$nextToken]['code'] === T_STRING + ) { + if ($tokens[$nextToken]['code'] === T_NEW) { + $currException = $phpcsFile->findNext( + [ + T_NS_SEPARATOR, + T_STRING, + ], + $currPos, + $stackPtrEnd, + false, + null, + true + ); + } else { + $currException = $nextToken; + } + + if ($currException !== false) { + $endException = $phpcsFile->findNext( + [ + T_NS_SEPARATOR, + T_STRING, + ], + ($currException + 1), + $stackPtrEnd, + true, + null, + true + ); + + if ($endException === false) { + $thrownExceptions[] = $tokens[$currException]['content']; + } else { + $thrownExceptions[] = $phpcsFile->getTokensAsString($currException, ($endException - $currException)); + } + }//end if + } else if ($tokens[$nextToken]['code'] === T_VARIABLE) { + // Find the nearest catch block in this scope and, if the caught var + // matches our re-thrown var, use the exception types being caught as + // exception types that are being thrown as well. + $catch = $phpcsFile->findPrevious( + T_CATCH, + $currPos, + $tokens[$stackPtr]['scope_opener'], + false, + null, + false + ); + + if ($catch !== false) { + $thrownVar = $phpcsFile->findPrevious( + T_VARIABLE, + ($tokens[$catch]['parenthesis_closer'] - 1), + $tokens[$catch]['parenthesis_opener'] + ); + + if ($tokens[$thrownVar]['content'] === $tokens[$nextToken]['content']) { + $exceptions = explode('|', $phpcsFile->getTokensAsString(($tokens[$catch]['parenthesis_opener'] + 1), ($thrownVar - $tokens[$catch]['parenthesis_opener'] - 1))); + foreach ($exceptions as $exception) { + $thrownExceptions[] = trim($exception); + } + } + } + } else { + ++$unknownCount; + }//end if + } while ($currPos < $stackPtrEnd && $currPos !== false); + + if ($foundThrows === false) { + return; + } + + // Only need one @throws tag for each type of exception thrown. + $thrownExceptions = array_unique($thrownExceptions); + + $throwTags = []; + $commentStart = $tokens[$commentEnd]['comment_opener']; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] !== '@throws') { + continue; + } + + if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) { + $exception = $tokens[($tag + 2)]['content']; + $space = strpos($exception, ' '); + if ($space !== false) { + $exception = substr($exception, 0, $space); + } + + $throwTags[$exception] = true; + } + } + + if (empty($throwTags) === true) { + $error = 'Missing @throws tag in function comment'; + $phpcsFile->addError($error, $commentEnd, 'Missing'); + return; + } else if (empty($thrownExceptions) === true) { + // If token count is zero, it means that only variables are being + // thrown, so we need at least one @throws tag (checked above). + // Nothing more to do. + return; + } + + // Make sure @throws tag count matches thrown count. + $thrownCount = (count($thrownExceptions) + $unknownCount); + $tagCount = count($throwTags); + if ($thrownCount !== $tagCount) { + $error = 'Expected %s @throws tag(s) in function comment; %s found'; + $data = [ + $thrownCount, + $tagCount, + ]; + $phpcsFile->addError($error, $commentEnd, 'WrongNumber', $data); + return; + } + + foreach ($thrownExceptions as $throw) { + if (isset($throwTags[$throw]) === true) { + continue; + } + + foreach ($throwTags as $tag => $ignore) { + if (strrpos($tag, $throw) === (strlen($tag) - strlen($throw))) { + continue 2; + } + } + + $error = 'Missing @throws tag for "%s" exception'; + $data = [$throw]; + $phpcsFile->addError($error, $commentEnd, 'Missing', $data); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php new file mode 100644 index 0000000..3c1ead7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php @@ -0,0 +1,349 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class InlineCommentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_COMMENT, + T_DOC_COMMENT_OPEN_TAG, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void|int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // If this is a function/class/interface doc block comment, skip it. + // We are only interested in inline doc block comments, which are + // not allowed. + if ($tokens[$stackPtr]['code'] === T_DOC_COMMENT_OPEN_TAG) { + $nextToken = $stackPtr; + do { + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] === T_ATTRIBUTE) { + $nextToken = $tokens[$nextToken]['attribute_closer']; + continue; + } + + break; + } while (true); + + $ignore = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + T_CLOSURE, + T_PUBLIC, + T_PRIVATE, + T_PROTECTED, + T_FINAL, + T_STATIC, + T_ABSTRACT, + T_READONLY, + T_CONST, + T_PROPERTY, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + ]; + + if (in_array($tokens[$nextToken]['code'], $ignore, true) === true) { + return; + } + + if ($phpcsFile->tokenizerType === 'JS') { + // We allow block comments if a function or object + // is being assigned to a variable. + $ignore = Tokens::$emptyTokens; + $ignore[] = T_EQUAL; + $ignore[] = T_STRING; + $ignore[] = T_OBJECT_OPERATOR; + $nextToken = $phpcsFile->findNext($ignore, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] === T_FUNCTION + || $tokens[$nextToken]['code'] === T_CLOSURE + || $tokens[$nextToken]['code'] === T_OBJECT + || $tokens[$nextToken]['code'] === T_PROTOTYPE + ) { + return; + } + } + + $prevToken = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($stackPtr - 1), + null, + true + ); + + if ($tokens[$prevToken]['code'] === T_OPEN_TAG) { + return; + } + + if ($tokens[$stackPtr]['content'] === '/**') { + $error = 'Inline doc block comments are not allowed; use "/* Comment */" or "// Comment" instead'; + $phpcsFile->addError($error, $stackPtr, 'DocBlock'); + } + }//end if + + if ($tokens[$stackPtr]['content'][0] === '#') { + $error = 'Perl-style comments are not allowed; use "// Comment" instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'WrongStyle'); + if ($fix === true) { + $comment = ltrim($tokens[$stackPtr]['content'], "# \t"); + $phpcsFile->fixer->replaceToken($stackPtr, "// $comment"); + } + } + + // We don't want end of block comments. Check if the last token before the + // comment is a closing curly brace. + $previousContent = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$previousContent]['line'] === $tokens[$stackPtr]['line']) { + if ($tokens[$previousContent]['code'] === T_CLOSE_CURLY_BRACKET) { + return; + } + + // Special case for JS files. + if ($tokens[$previousContent]['code'] === T_COMMA + || $tokens[$previousContent]['code'] === T_SEMICOLON + ) { + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($previousContent - 1), null, true); + if ($tokens[$lastContent]['code'] === T_CLOSE_CURLY_BRACKET) { + return; + } + } + } + + // Only want inline comments. + if (substr($tokens[$stackPtr]['content'], 0, 2) !== '//') { + return; + } + + $commentTokens = [$stackPtr]; + + $nextComment = $stackPtr; + $lastComment = $stackPtr; + while (($nextComment = $phpcsFile->findNext(T_COMMENT, ($nextComment + 1), null, false)) !== false) { + if ($tokens[$nextComment]['line'] !== ($tokens[$lastComment]['line'] + 1)) { + break; + } + + // Only want inline comments. + if (substr($tokens[$nextComment]['content'], 0, 2) !== '//') { + break; + } + + // There is a comment on the very next line. If there is + // no code between the comments, they are part of the same + // comment block. + $prevNonWhitespace = $phpcsFile->findPrevious(T_WHITESPACE, ($nextComment - 1), $lastComment, true); + if ($prevNonWhitespace !== $lastComment) { + break; + } + + $commentTokens[] = $nextComment; + $lastComment = $nextComment; + }//end while + + $commentText = ''; + foreach ($commentTokens as $lastCommentToken) { + $comment = rtrim($tokens[$lastCommentToken]['content']); + + if (trim(substr($comment, 2)) === '') { + continue; + } + + $spaceCount = 0; + $tabFound = false; + + $commentLength = strlen($comment); + for ($i = 2; $i < $commentLength; $i++) { + if ($comment[$i] === "\t") { + $tabFound = true; + break; + } + + if ($comment[$i] !== ' ') { + break; + } + + $spaceCount++; + } + + $fix = false; + if ($tabFound === true) { + $error = 'Tab found before comment text; expected "// %s" but found "%s"'; + $data = [ + ltrim(substr($comment, 2)), + $comment, + ]; + $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'TabBefore', $data); + } else if ($spaceCount === 0) { + $error = 'No space found before comment text; expected "// %s" but found "%s"'; + $data = [ + substr($comment, 2), + $comment, + ]; + $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'NoSpaceBefore', $data); + } else if ($spaceCount > 1) { + $error = 'Expected 1 space before comment text but found %s; use block comment if you need indentation'; + $data = [ + $spaceCount, + substr($comment, (2 + $spaceCount)), + $comment, + ]; + $fix = $phpcsFile->addFixableError($error, $lastCommentToken, 'SpacingBefore', $data); + }//end if + + if ($fix === true) { + $newComment = '// '.ltrim($tokens[$lastCommentToken]['content'], "/\t "); + $phpcsFile->fixer->replaceToken($lastCommentToken, $newComment); + } + + $commentText .= trim(substr($tokens[$lastCommentToken]['content'], 2)); + }//end foreach + + if ($commentText === '') { + $error = 'Blank comments are not allowed'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Empty'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, ''); + } + + return ($lastCommentToken + 1); + } + + if (preg_match('/^\p{Ll}/u', $commentText) === 1) { + $error = 'Inline comments must start with a capital letter'; + $phpcsFile->addError($error, $stackPtr, 'NotCapital'); + } + + // Only check the end of comment character if the start of the comment + // is a letter, indicating that the comment is just standard text. + if (preg_match('/^\p{L}/u', $commentText) === 1) { + $commentCloser = $commentText[(strlen($commentText) - 1)]; + $acceptedClosers = [ + 'full-stops' => '.', + 'exclamation marks' => '!', + 'or question marks' => '?', + ]; + + if (in_array($commentCloser, $acceptedClosers, true) === false) { + $error = 'Inline comments must end in %s'; + $ender = ''; + foreach ($acceptedClosers as $closerName => $symbol) { + $ender .= ' '.$closerName.','; + } + + $ender = trim($ender, ' ,'); + $data = [$ender]; + $phpcsFile->addError($error, $lastCommentToken, 'InvalidEndChar', $data); + } + } + + // Finally, the line below the last comment cannot be empty if this inline + // comment is on a line by itself. + if ($tokens[$previousContent]['line'] < $tokens[$stackPtr]['line']) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($lastCommentToken + 1), null, true); + if ($next === false) { + // Ignore if the comment is the last non-whitespace token in a file. + return ($lastCommentToken + 1); + } + + if ($tokens[$next]['code'] === T_DOC_COMMENT_OPEN_TAG) { + // If this inline comment is followed by a docblock, + // ignore spacing as docblock/function etc spacing rules + // are likely to conflict with our rules. + return ($lastCommentToken + 1); + } + + $errorCode = 'SpacingAfter'; + + if (isset($tokens[$stackPtr]['conditions']) === true) { + $conditions = $tokens[$stackPtr]['conditions']; + $type = end($conditions); + $conditionPtr = key($conditions); + + if (($type === T_FUNCTION || $type === T_CLOSURE) + && $tokens[$conditionPtr]['scope_closer'] === $next + ) { + $errorCode = 'SpacingAfterAtFunctionEnd'; + } + } + + for ($i = ($lastCommentToken + 1); $i < $phpcsFile->numTokens; $i++) { + if ($tokens[$i]['line'] === ($tokens[$lastCommentToken]['line'] + 1)) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + return ($lastCommentToken + 1); + } + } else if ($tokens[$i]['line'] > ($tokens[$lastCommentToken]['line'] + 1)) { + break; + } + } + + $error = 'There must be no blank line following an inline comment'; + $fix = $phpcsFile->addFixableError($error, $lastCommentToken, $errorCode); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($lastCommentToken + 1); $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + return ($lastCommentToken + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/LongConditionClosingCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/LongConditionClosingCommentSniff.php new file mode 100644 index 0000000..439fc38 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/LongConditionClosingCommentSniff.php @@ -0,0 +1,218 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class LongConditionClosingCommentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The openers that we are interested in. + * + * @var integer[] + */ + private static $openers = [ + T_SWITCH, + T_IF, + T_FOR, + T_FOREACH, + T_WHILE, + T_TRY, + T_CASE, + T_MATCH, + ]; + + /** + * The length that a code block must be before + * requiring a closing comment. + * + * @var integer + */ + public $lineLimit = 20; + + /** + * The format the end comment should be in. + * + * The placeholder %s will be replaced with the type of condition opener. + * + * @var string + */ + public $commentFormat = '//end %s'; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_CLOSE_CURLY_BRACKET]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_condition']) === false) { + // No scope condition. It is a function closer. + return; + } + + $startCondition = $tokens[$tokens[$stackPtr]['scope_condition']]; + $startBrace = $tokens[$tokens[$stackPtr]['scope_opener']]; + $endBrace = $tokens[$stackPtr]; + + // We are only interested in some code blocks. + if (in_array($startCondition['code'], self::$openers, true) === false) { + return; + } + + if ($startCondition['code'] === T_IF) { + // If this is actually an ELSE IF, skip it as the brace + // will be checked by the original IF. + $else = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$stackPtr]['scope_condition'] - 1), null, true); + if ($tokens[$else]['code'] === T_ELSE) { + return; + } + + // IF statements that have an ELSE block need to use + // "end if" rather than "end else" or "end elseif". + do { + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$nextToken]['code'] === T_ELSE || $tokens[$nextToken]['code'] === T_ELSEIF) { + // Check for ELSE IF (2 tokens) as opposed to ELSEIF (1 token). + if ($tokens[$nextToken]['code'] === T_ELSE + && isset($tokens[$nextToken]['scope_closer']) === false + ) { + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); + if ($tokens[$nextToken]['code'] !== T_IF + || isset($tokens[$nextToken]['scope_closer']) === false + ) { + // Not an ELSE IF or is an inline ELSE IF. + break; + } + } + + if (isset($tokens[$nextToken]['scope_closer']) === false) { + // There isn't going to be anywhere to print the "end if" comment + // because there is no closer. + return; + } + + // The end brace becomes the ELSE's end brace. + $stackPtr = $tokens[$nextToken]['scope_closer']; + $endBrace = $tokens[$stackPtr]; + } else { + break; + }//end if + } while (isset($tokens[$nextToken]['scope_closer']) === true); + }//end if + + if ($startCondition['code'] === T_TRY) { + // TRY statements need to check until the end of all CATCH statements. + do { + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$nextToken]['code'] === T_CATCH + || $tokens[$nextToken]['code'] === T_FINALLY + ) { + // The end brace becomes the CATCH end brace. + $stackPtr = $tokens[$nextToken]['scope_closer']; + $endBrace = $tokens[$stackPtr]; + } else { + break; + } + } while (isset($tokens[$nextToken]['scope_closer']) === true); + } + + if ($startCondition['code'] === T_MATCH) { + // Move the stackPtr to after the semi-colon/comma if there is one. + $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($nextToken !== false + && ($tokens[$nextToken]['code'] === T_SEMICOLON + || $tokens[$nextToken]['code'] === T_COMMA) + ) { + $stackPtr = $nextToken; + } + } + + $lineDifference = ($endBrace['line'] - $startBrace['line']); + + $expected = sprintf($this->commentFormat, $startCondition['content']); + $comment = $phpcsFile->findNext([T_COMMENT], $stackPtr, null, false); + + if (($comment === false) || ($tokens[$comment]['line'] !== $endBrace['line'])) { + if ($lineDifference >= $this->lineLimit) { + $error = 'End comment for long condition not found; expected "%s"'; + $data = [$expected]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Missing', $data); + + if ($fix === true) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($next !== false && $tokens[$next]['line'] === $tokens[$stackPtr]['line']) { + $expected .= $phpcsFile->eolChar; + } + + $phpcsFile->fixer->addContent($stackPtr, $expected); + } + } + + return; + } + + if (($comment - $stackPtr) !== 1) { + $error = 'Space found before closing comment; expected "%s"'; + $data = [$expected]; + $phpcsFile->addError($error, $stackPtr, 'SpacingBefore', $data); + } + + if (trim($tokens[$comment]['content']) !== $expected) { + $found = trim($tokens[$comment]['content']); + $error = 'Incorrect closing comment; expected "%s" but found "%s"'; + $data = [ + $expected, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Invalid', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($comment, $expected.$phpcsFile->eolChar); + } + + return; + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php new file mode 100644 index 0000000..9b36abe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php @@ -0,0 +1,121 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class PostStatementCommentSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * Exceptions to the rule. + * + * If post statement comments are found within the condition + * parenthesis of these structures, leave them alone. + * + * @var array + */ + private $controlStructureExceptions = [ + T_IF => true, + T_ELSEIF => true, + T_SWITCH => true, + T_WHILE => true, + T_FOR => true, + T_FOREACH => true, + T_MATCH => true, + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_COMMENT]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (substr($tokens[$stackPtr]['content'], 0, 2) !== '//') { + return; + } + + $commentLine = $tokens[$stackPtr]['line']; + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + + if ($lastContent === false + || $tokens[$lastContent]['line'] !== $commentLine + || $tokens[$stackPtr]['column'] === 1 + ) { + return; + } + + if ($tokens[$lastContent]['code'] === T_CLOSE_CURLY_BRACKET) { + return; + } + + // Special case for JS files and PHP closures. + if ($tokens[$lastContent]['code'] === T_COMMA + || $tokens[$lastContent]['code'] === T_SEMICOLON + ) { + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($lastContent - 1), null, true); + if ($lastContent === false || $tokens[$lastContent]['code'] === T_CLOSE_CURLY_BRACKET) { + return; + } + } + + // Special case for (trailing) comments within multi-line control structures. + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $nestedParens = $tokens[$stackPtr]['nested_parenthesis']; + foreach ($nestedParens as $open => $close) { + if (isset($tokens[$open]['parenthesis_owner']) === true + && isset($this->controlStructureExceptions[$tokens[$tokens[$open]['parenthesis_owner']]['code']]) === true + ) { + return; + } + } + } + + $error = 'Comments may not appear after statements'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($stackPtr); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php new file mode 100644 index 0000000..76fbc6d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php @@ -0,0 +1,201 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; +use PHP_CodeSniffer\Util\Common; + +class VariableCommentSniff extends AbstractVariableSniff +{ + + + /** + * Called to process class member vars. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $ignore = [ + T_PUBLIC => T_PUBLIC, + T_PRIVATE => T_PRIVATE, + T_PROTECTED => T_PROTECTED, + T_VAR => T_VAR, + T_STATIC => T_STATIC, + T_READONLY => T_READONLY, + T_WHITESPACE => T_WHITESPACE, + T_STRING => T_STRING, + T_NS_SEPARATOR => T_NS_SEPARATOR, + T_NAMESPACE => T_NAMESPACE, + T_NULLABLE => T_NULLABLE, + T_TYPE_UNION => T_TYPE_UNION, + T_TYPE_INTERSECTION => T_TYPE_INTERSECTION, + T_NULL => T_NULL, + T_TRUE => T_TRUE, + T_FALSE => T_FALSE, + T_SELF => T_SELF, + T_PARENT => T_PARENT, + ]; + + for ($commentEnd = ($stackPtr - 1); $commentEnd >= 0; $commentEnd--) { + if (isset($ignore[$tokens[$commentEnd]['code']]) === true) { + continue; + } + + if ($tokens[$commentEnd]['code'] === T_ATTRIBUTE_END + && isset($tokens[$commentEnd]['attribute_opener']) === true + ) { + $commentEnd = $tokens[$commentEnd]['attribute_opener']; + continue; + } + + break; + } + + if ($commentEnd === false + || ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG + && $tokens[$commentEnd]['code'] !== T_COMMENT) + ) { + $phpcsFile->addError('Missing member variable doc comment', $stackPtr, 'Missing'); + return; + } + + if ($tokens[$commentEnd]['code'] === T_COMMENT) { + $phpcsFile->addError('You must use "/**" style comments for a member variable comment', $stackPtr, 'WrongStyle'); + return; + } + + $commentStart = $tokens[$commentEnd]['comment_opener']; + + $foundVar = null; + foreach ($tokens[$commentStart]['comment_tags'] as $tag) { + if ($tokens[$tag]['content'] === '@var') { + if ($foundVar !== null) { + $error = 'Only one @var tag is allowed in a member variable comment'; + $phpcsFile->addError($error, $tag, 'DuplicateVar'); + } else { + $foundVar = $tag; + } + } else if ($tokens[$tag]['content'] === '@see') { + // Make sure the tag isn't empty. + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) { + $error = 'Content missing for @see tag in member variable comment'; + $phpcsFile->addError($error, $tag, 'EmptySees'); + } + } else { + $error = '%s tag is not allowed in member variable comment'; + $data = [$tokens[$tag]['content']]; + $phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data); + }//end if + }//end foreach + + // The @var tag is the only one we require. + if ($foundVar === null) { + $error = 'Missing @var tag in member variable comment'; + $phpcsFile->addError($error, $commentEnd, 'MissingVar'); + return; + } + + $firstTag = $tokens[$commentStart]['comment_tags'][0]; + if ($foundVar !== null && $tokens[$firstTag]['content'] !== '@var') { + $error = 'The @var tag must be the first tag in a member variable comment'; + $phpcsFile->addError($error, $foundVar, 'VarOrder'); + } + + // Make sure the tag isn't empty and has the correct padding. + $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $foundVar, $commentEnd); + if ($string === false || $tokens[$string]['line'] !== $tokens[$foundVar]['line']) { + $error = 'Content missing for @var tag in member variable comment'; + $phpcsFile->addError($error, $foundVar, 'EmptyVar'); + return; + } + + // Support both a var type and a description. + preg_match('`^((?:\|?(?:array\([^\)]*\)|[\\\\a-z0-9\[\]]+))*)( .*)?`i', $tokens[($foundVar + 2)]['content'], $varParts); + if (isset($varParts[1]) === false) { + return; + } + + $varType = $varParts[1]; + + // Check var type (can be multiple, separated by '|'). + $typeNames = explode('|', $varType); + $suggestedNames = []; + foreach ($typeNames as $i => $typeName) { + $suggestedName = Common::suggestType($typeName); + if (in_array($suggestedName, $suggestedNames, true) === false) { + $suggestedNames[] = $suggestedName; + } + } + + $suggestedType = implode('|', $suggestedNames); + if ($varType !== $suggestedType) { + $error = 'Expected "%s" but found "%s" for @var tag in member variable comment'; + $data = [ + $suggestedType, + $varType, + ]; + $fix = $phpcsFile->addFixableError($error, $foundVar, 'IncorrectVarType', $data); + if ($fix === true) { + $replacement = $suggestedType; + if (empty($varParts[2]) === false) { + $replacement .= $varParts[2]; + } + + $phpcsFile->fixer->replaceToken(($foundVar + 2), $replacement); + unset($replacement); + } + } + + }//end processMemberVar() + + + /** + * Called to process a normal variable. + * + * Not required for this sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this token was found. + * @param int $stackPtr The position where the double quoted + * string was found. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + + }//end processVariable() + + + /** + * Called to process variables found in double quoted strings. + * + * Not required for this sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this token was found. + * @param int $stackPtr The position where the double quoted + * string was found. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php new file mode 100644 index 0000000..06fd3ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php @@ -0,0 +1,337 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ControlSignatureSniff implements Sniff +{ + + /** + * How many spaces should precede the colon if using alternative syntax. + * + * @var integer + */ + public $requiredSpacesBeforeColon = 1; + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_TRY, + T_CATCH, + T_FINALLY, + T_DO, + T_WHILE, + T_FOR, + T_IF, + T_FOREACH, + T_ELSE, + T_ELSEIF, + T_SWITCH, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($nextNonEmpty === false) { + return; + } + + $isAlternative = false; + if (isset($tokens[$stackPtr]['scope_opener']) === true + && $tokens[$tokens[$stackPtr]['scope_opener']]['code'] === T_COLON + ) { + $isAlternative = true; + } + + // Single space after the keyword. + $expected = 1; + if (isset($tokens[$stackPtr]['parenthesis_closer']) === false && $isAlternative === true) { + // Catching cases like: + // if (condition) : ... else: ... endif + // where there is no condition. + $expected = (int) $this->requiredSpacesBeforeColon; + } + + $found = 1; + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $found = 0; + } else if ($tokens[($stackPtr + 1)]['content'] !== ' ') { + if (strpos($tokens[($stackPtr + 1)]['content'], $phpcsFile->eolChar) !== false) { + $found = 'newline'; + } else { + $found = $tokens[($stackPtr + 1)]['length']; + } + } + + if ($found !== $expected) { + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Expected %s space%s after %s keyword; %s found'; + $data = [ + $expected, + $pluralizeSpace, + strtoupper($tokens[$stackPtr]['content']), + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterKeyword', $data); + if ($fix === true) { + if ($found === 0) { + $phpcsFile->fixer->addContent($stackPtr, str_repeat(' ', $expected)); + } else { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), str_repeat(' ', $expected)); + } + } + }//end if + + // Single space after closing parenthesis. + if (isset($tokens[$stackPtr]['parenthesis_closer']) === true + && isset($tokens[$stackPtr]['scope_opener']) === true + ) { + $expected = 1; + if ($isAlternative === true) { + $expected = (int) $this->requiredSpacesBeforeColon; + } + + $closer = $tokens[$stackPtr]['parenthesis_closer']; + $opener = $tokens[$stackPtr]['scope_opener']; + $content = $phpcsFile->getTokensAsString(($closer + 1), ($opener - $closer - 1)); + + if (trim($content) === '') { + if (strpos($content, $phpcsFile->eolChar) !== false) { + $found = 'newline'; + } else { + $found = strlen($content); + } + } else { + $found = '"'.str_replace($phpcsFile->eolChar, '\n', $content).'"'; + } + + if ($found !== $expected) { + $pluralizeSpace = 's'; + if ($expected === 1) { + $pluralizeSpace = ''; + } + + $error = 'Expected %s space%s after closing parenthesis; found %s'; + $data = [ + $expected, + $pluralizeSpace, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $closer, 'SpaceAfterCloseParenthesis', $data); + if ($fix === true) { + $padding = str_repeat(' ', $expected); + if ($closer === ($opener - 1)) { + $phpcsFile->fixer->addContent($closer, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + if (trim($content) === '') { + $phpcsFile->fixer->addContent($closer, $padding); + if ($found !== 0) { + for ($i = ($closer + 1); $i < $opener; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + } else { + $phpcsFile->fixer->addContent($closer, $padding.$tokens[$opener]['content']); + $phpcsFile->fixer->replaceToken($opener, ''); + + if ($tokens[$opener]['line'] !== $tokens[$closer]['line']) { + $next = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true); + if ($tokens[$next]['line'] !== $tokens[$opener]['line']) { + for ($i = ($opener + 1); $i < $next; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + } + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + }//end if + }//end if + + // Single newline after opening brace. + if (isset($tokens[$stackPtr]['scope_opener']) === true) { + $opener = $tokens[$stackPtr]['scope_opener']; + for ($next = ($opener + 1); $next < $phpcsFile->numTokens; $next++) { + $code = $tokens[$next]['code']; + + if ($code === T_WHITESPACE + || ($code === T_INLINE_HTML + && trim($tokens[$next]['content']) === '') + ) { + continue; + } + + // Skip all empty tokens on the same line as the opener. + if ($tokens[$next]['line'] === $tokens[$opener]['line'] + && (isset(Tokens::$emptyTokens[$code]) === true + || $code === T_CLOSE_TAG) + ) { + continue; + } + + // We found the first bit of a code, or a comment on the + // following line. + break; + }//end for + + if ($tokens[$next]['line'] === $tokens[$opener]['line']) { + $error = 'Newline required after opening brace'; + $fix = $phpcsFile->addFixableError($error, $opener, 'NewlineAfterOpenBrace'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($opener + 1); $i < $next; $i++) { + if (trim($tokens[$i]['content']) !== '') { + break; + } + + // Remove whitespace. + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addContent($opener, $phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + }//end if + } else if ($tokens[$stackPtr]['code'] === T_WHILE) { + // Zero spaces after parenthesis closer, but only if followed by a semicolon. + $closer = $tokens[$stackPtr]['parenthesis_closer']; + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($closer + 1), null, true); + if ($nextNonEmpty !== false && $tokens[$nextNonEmpty]['code'] === T_SEMICOLON) { + $found = 0; + if ($tokens[($closer + 1)]['code'] === T_WHITESPACE) { + if (strpos($tokens[($closer + 1)]['content'], $phpcsFile->eolChar) !== false) { + $found = 'newline'; + } else { + $found = $tokens[($closer + 1)]['length']; + } + } + + if ($found !== 0) { + $error = 'Expected 0 spaces before semicolon; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $closer, 'SpaceBeforeSemicolon', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($closer + 1), ''); + } + } + } + }//end if + + // Only want to check multi-keyword structures from here on. + if ($tokens[$stackPtr]['code'] === T_WHILE) { + if (isset($tokens[$stackPtr]['scope_closer']) !== false) { + return; + } + + $closer = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($closer === false + || $tokens[$closer]['code'] !== T_CLOSE_CURLY_BRACKET + || $tokens[$tokens[$closer]['scope_condition']]['code'] !== T_DO + ) { + return; + } + } else if ($tokens[$stackPtr]['code'] === T_ELSE + || $tokens[$stackPtr]['code'] === T_ELSEIF + || $tokens[$stackPtr]['code'] === T_CATCH + || $tokens[$stackPtr]['code'] === T_FINALLY + ) { + if (isset($tokens[$stackPtr]['scope_opener']) === true + && $tokens[$tokens[$stackPtr]['scope_opener']]['code'] === T_COLON + ) { + // Special case for alternate syntax, where this token is actually + // the closer for the previous block, so there is no spacing to check. + return; + } + + $closer = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($closer === false || $tokens[$closer]['code'] !== T_CLOSE_CURLY_BRACKET) { + return; + } + } else { + return; + }//end if + + // Single space after closing brace. + $found = 1; + if ($tokens[($closer + 1)]['code'] !== T_WHITESPACE) { + $found = 0; + } else if ($tokens[$closer]['line'] !== $tokens[$stackPtr]['line']) { + $found = 'newline'; + } else if ($tokens[($closer + 1)]['content'] !== ' ') { + $found = $tokens[($closer + 1)]['length']; + } + + if ($found !== 1) { + $error = 'Expected 1 space after closing brace; %s found'; + $data = [$found]; + + if ($phpcsFile->findNext(Tokens::$commentTokens, ($closer + 1), $stackPtr) !== false) { + // Comment found between closing brace and keyword, don't auto-fix. + $phpcsFile->addError($error, $closer, 'SpaceAfterCloseBrace', $data); + return; + } + + $fix = $phpcsFile->addFixableError($error, $closer, 'SpaceAfterCloseBrace', $data); + if ($fix === true) { + if ($found === 0) { + $phpcsFile->fixer->addContent($closer, ' '); + } else { + $phpcsFile->fixer->replaceToken(($closer + 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ElseIfDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ElseIfDeclarationSniff.php new file mode 100644 index 0000000..3cdb901 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ElseIfDeclarationSniff.php @@ -0,0 +1,51 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ElseIfDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_ELSEIF]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $error = 'Usage of ELSEIF not allowed; use ELSE IF instead'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAllowed'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, 'else if'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForEachLoopDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForEachLoopDeclarationSniff.php new file mode 100644 index 0000000..bd51b26 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForEachLoopDeclarationSniff.php @@ -0,0 +1,236 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ForEachLoopDeclarationSniff implements Sniff +{ + + /** + * How many spaces should follow the opening bracket. + * + * @var integer + */ + public $requiredSpacesAfterOpen = 0; + + /** + * How many spaces should precede the closing bracket. + * + * @var integer + */ + public $requiredSpacesBeforeClose = 0; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FOREACH]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $this->requiredSpacesAfterOpen = (int) $this->requiredSpacesAfterOpen; + $this->requiredSpacesBeforeClose = (int) $this->requiredSpacesBeforeClose; + $tokens = $phpcsFile->getTokens(); + + $openingBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, $stackPtr); + if ($openingBracket === false) { + $error = 'Possible parse error: FOREACH has no opening parenthesis'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingOpenParenthesis'); + return; + } + + if (isset($tokens[$openingBracket]['parenthesis_closer']) === false) { + $error = 'Possible parse error: FOREACH has no closing parenthesis'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingCloseParenthesis'); + return; + } + + $closingBracket = $tokens[$openingBracket]['parenthesis_closer']; + + if ($this->requiredSpacesAfterOpen === 0 && $tokens[($openingBracket + 1)]['code'] === T_WHITESPACE) { + $error = 'Space found after opening bracket of FOREACH loop'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterOpen'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($openingBracket + 1), ''); + } + } else if ($this->requiredSpacesAfterOpen > 0) { + $spaceAfterOpen = 0; + if ($tokens[($openingBracket + 1)]['code'] === T_WHITESPACE) { + $spaceAfterOpen = $tokens[($openingBracket + 1)]['length']; + } + + if ($spaceAfterOpen !== $this->requiredSpacesAfterOpen) { + $error = 'Expected %s spaces after opening bracket; %s found'; + $data = [ + $this->requiredSpacesAfterOpen, + $spaceAfterOpen, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterOpen', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesAfterOpen); + if ($spaceAfterOpen === 0) { + $phpcsFile->fixer->addContent($openingBracket, $padding); + } else { + $phpcsFile->fixer->replaceToken(($openingBracket + 1), $padding); + } + } + } + }//end if + + if ($this->requiredSpacesBeforeClose === 0 && $tokens[($closingBracket - 1)]['code'] === T_WHITESPACE) { + $error = 'Space found before closing bracket of FOREACH loop'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeClose'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($closingBracket - 1), ''); + } + } else if ($this->requiredSpacesBeforeClose > 0) { + $spaceBeforeClose = 0; + if ($tokens[($closingBracket - 1)]['code'] === T_WHITESPACE) { + $spaceBeforeClose = $tokens[($closingBracket - 1)]['length']; + } + + if ($spaceBeforeClose !== $this->requiredSpacesBeforeClose) { + $error = 'Expected %s spaces before closing bracket; %s found'; + $data = [ + $this->requiredSpacesBeforeClose, + $spaceBeforeClose, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBeforeClose', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesBeforeClose); + if ($spaceBeforeClose === 0) { + $phpcsFile->fixer->addContentBefore($closingBracket, $padding); + } else { + $phpcsFile->fixer->replaceToken(($closingBracket - 1), $padding); + } + } + } + }//end if + + $asToken = $phpcsFile->findNext(T_AS, $openingBracket); + if ($asToken === false) { + $error = 'Possible parse error: FOREACH has no AS statement'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingAs'); + return; + } + + $content = $tokens[$asToken]['content']; + if ($content !== strtolower($content)) { + $expected = strtolower($content); + $error = 'AS keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + $expected, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $asToken, 'AsNotLower', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($asToken, $expected); + } + } + + $doubleArrow = $phpcsFile->findNext(T_DOUBLE_ARROW, $asToken, $closingBracket); + + if ($doubleArrow !== false) { + if ($tokens[($doubleArrow - 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space before "=>"; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBeforeArrow'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($doubleArrow, ' '); + } + } else { + if ($tokens[($doubleArrow - 1)]['length'] !== 1) { + $spaces = $tokens[($doubleArrow - 1)]['length']; + $error = 'Expected 1 space before "=>"; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBeforeArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($doubleArrow - 1), ' '); + } + } + } + + if ($tokens[($doubleArrow + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space after "=>"; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfterArrow'); + if ($fix === true) { + $phpcsFile->fixer->addContent($doubleArrow, ' '); + } + } else { + if ($tokens[($doubleArrow + 1)]['length'] !== 1) { + $spaces = $tokens[($doubleArrow + 1)]['length']; + $error = 'Expected 1 space after "=>"; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterArrow', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($doubleArrow + 1), ' '); + } + } + } + }//end if + + if ($tokens[($asToken - 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space before "as"; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBeforeAs'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($asToken, ' '); + } + } else { + if ($tokens[($asToken - 1)]['length'] !== 1) { + $spaces = $tokens[($asToken - 1)]['length']; + $error = 'Expected 1 space before "as"; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBeforeAs', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($asToken - 1), ' '); + } + } + } + + if ($tokens[($asToken + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space after "as"; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfterAs'); + if ($fix === true) { + $phpcsFile->fixer->addContent($asToken, ' '); + } + } else { + if ($tokens[($asToken + 1)]['length'] !== 1) { + $spaces = $tokens[($asToken + 1)]['length']; + $error = 'Expected 1 space after "as"; %s found'; + $data = [$spaces]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterAs', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($asToken + 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForLoopDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForLoopDeclarationSniff.php new file mode 100644 index 0000000..e5e4e66 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForLoopDeclarationSniff.php @@ -0,0 +1,316 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ForLoopDeclarationSniff implements Sniff +{ + + /** + * How many spaces should follow the opening bracket. + * + * @var integer + */ + public $requiredSpacesAfterOpen = 0; + + /** + * How many spaces should precede the closing bracket. + * + * @var integer + */ + public $requiredSpacesBeforeClose = 0; + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FOR]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $this->requiredSpacesAfterOpen = (int) $this->requiredSpacesAfterOpen; + $this->requiredSpacesBeforeClose = (int) $this->requiredSpacesBeforeClose; + $tokens = $phpcsFile->getTokens(); + + $openingBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, $stackPtr); + if ($openingBracket === false) { + $error = 'Possible parse error: no opening parenthesis for FOR keyword'; + $phpcsFile->addWarning($error, $stackPtr, 'NoOpenBracket'); + return; + } + + $closingBracket = $tokens[$openingBracket]['parenthesis_closer']; + + if ($this->requiredSpacesAfterOpen === 0 + && $tokens[($openingBracket + 1)]['code'] === T_WHITESPACE + ) { + $nextNonWhiteSpace = $phpcsFile->findNext(T_WHITESPACE, ($openingBracket + 1), $closingBracket, true); + if ($this->ignoreNewlines === false + || $tokens[$nextNonWhiteSpace]['line'] === $tokens[$openingBracket]['line'] + ) { + $error = 'Whitespace found after opening bracket of FOR loop'; + $fix = $phpcsFile->addFixableError($error, $openingBracket, 'SpacingAfterOpen'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($openingBracket + 1); $i < $closingBracket; $i++) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + } else if ($this->requiredSpacesAfterOpen > 0) { + $nextNonWhiteSpace = $phpcsFile->findNext(T_WHITESPACE, ($openingBracket + 1), $closingBracket, true); + $spaceAfterOpen = 0; + if ($tokens[$openingBracket]['line'] !== $tokens[$nextNonWhiteSpace]['line']) { + $spaceAfterOpen = 'newline'; + } else if ($tokens[($openingBracket + 1)]['code'] === T_WHITESPACE) { + $spaceAfterOpen = $tokens[($openingBracket + 1)]['length']; + } + + if ($spaceAfterOpen !== $this->requiredSpacesAfterOpen + && ($this->ignoreNewlines === false + || $spaceAfterOpen !== 'newline') + ) { + $error = 'Expected %s spaces after opening bracket; %s found'; + $data = [ + $this->requiredSpacesAfterOpen, + $spaceAfterOpen, + ]; + $fix = $phpcsFile->addFixableError($error, $openingBracket, 'SpacingAfterOpen', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesAfterOpen); + if ($spaceAfterOpen === 0) { + $phpcsFile->fixer->addContent($openingBracket, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($openingBracket + 1), $padding); + for ($i = ($openingBracket + 2); $i < $nextNonWhiteSpace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + }//end if + + $prevNonWhiteSpace = $phpcsFile->findPrevious(T_WHITESPACE, ($closingBracket - 1), $openingBracket, true); + $beforeClosefixable = true; + if ($tokens[$prevNonWhiteSpace]['line'] !== $tokens[$closingBracket]['line'] + && isset(Tokens::$emptyTokens[$tokens[$prevNonWhiteSpace]['code']]) === true + ) { + $beforeClosefixable = false; + } + + if ($this->requiredSpacesBeforeClose === 0 + && $tokens[($closingBracket - 1)]['code'] === T_WHITESPACE + && ($this->ignoreNewlines === false + || $tokens[$prevNonWhiteSpace]['line'] === $tokens[$closingBracket]['line']) + ) { + $error = 'Whitespace found before closing bracket of FOR loop'; + + if ($beforeClosefixable === false) { + $phpcsFile->addError($error, $closingBracket, 'SpacingBeforeClose'); + } else { + $fix = $phpcsFile->addFixableError($error, $closingBracket, 'SpacingBeforeClose'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($closingBracket - 1); $i > $openingBracket; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + } else if ($this->requiredSpacesBeforeClose > 0) { + $spaceBeforeClose = 0; + if ($tokens[$closingBracket]['line'] !== $tokens[$prevNonWhiteSpace]['line']) { + $spaceBeforeClose = 'newline'; + } else if ($tokens[($closingBracket - 1)]['code'] === T_WHITESPACE) { + $spaceBeforeClose = $tokens[($closingBracket - 1)]['length']; + } + + if ($this->requiredSpacesBeforeClose !== $spaceBeforeClose + && ($this->ignoreNewlines === false + || $spaceBeforeClose !== 'newline') + ) { + $error = 'Expected %s spaces before closing bracket; %s found'; + $data = [ + $this->requiredSpacesBeforeClose, + $spaceBeforeClose, + ]; + + if ($beforeClosefixable === false) { + $phpcsFile->addError($error, $closingBracket, 'SpacingBeforeClose', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $closingBracket, 'SpacingBeforeClose', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesBeforeClose); + if ($spaceBeforeClose === 0) { + $phpcsFile->fixer->addContentBefore($closingBracket, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($closingBracket - 1), $padding); + for ($i = ($closingBracket - 2); $i > $prevNonWhiteSpace; $i--) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + } + }//end if + }//end if + + /* + * Check whitespace around each of the semicolon tokens. + */ + + $semicolonCount = 0; + $semicolon = $openingBracket; + $targetNestinglevel = 0; + if (isset($tokens[$openingBracket]['conditions']) === true) { + $targetNestinglevel = count($tokens[$openingBracket]['conditions']); + } + + do { + $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($semicolon + 1), $closingBracket); + if ($semicolon === false) { + break; + } + + if (isset($tokens[$semicolon]['conditions']) === true + && count($tokens[$semicolon]['conditions']) > $targetNestinglevel + ) { + // Semicolon doesn't belong to the for(). + continue; + } + + ++$semicolonCount; + + $humanReadableCount = 'first'; + if ($semicolonCount !== 1) { + $humanReadableCount = 'second'; + } + + $humanReadableCode = ucfirst($humanReadableCount); + $data = [$humanReadableCount]; + + // Only examine the space before the first semicolon if the first expression is not empty. + // If it *is* empty, leave it up to the `SpacingAfterOpen` logic. + $prevNonWhiteSpace = $phpcsFile->findPrevious(T_WHITESPACE, ($semicolon - 1), $openingBracket, true); + if ($semicolonCount !== 1 || $prevNonWhiteSpace !== $openingBracket) { + if ($tokens[($semicolon - 1)]['code'] === T_WHITESPACE) { + $error = 'Whitespace found before %s semicolon of FOR loop'; + $errorCode = 'SpacingBefore'.$humanReadableCode; + $fix = $phpcsFile->addFixableError($error, $semicolon, $errorCode, $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($semicolon - 1); $i > $prevNonWhiteSpace; $i--) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + } + + // Only examine the space after the second semicolon if the last expression is not empty. + // If it *is* empty, leave it up to the `SpacingBeforeClose` logic. + $nextNonWhiteSpace = $phpcsFile->findNext(T_WHITESPACE, ($semicolon + 1), ($closingBracket + 1), true); + if ($semicolonCount !== 2 || $nextNonWhiteSpace !== $closingBracket) { + if ($tokens[($semicolon + 1)]['code'] !== T_WHITESPACE + && $tokens[($semicolon + 1)]['code'] !== T_SEMICOLON + ) { + $error = 'Expected 1 space after %s semicolon of FOR loop; 0 found'; + $errorCode = 'NoSpaceAfter'.$humanReadableCode; + $fix = $phpcsFile->addFixableError($error, $semicolon, $errorCode, $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($semicolon, ' '); + } + } else if ($tokens[($semicolon + 1)]['code'] === T_WHITESPACE + && $tokens[$nextNonWhiteSpace]['code'] !== T_SEMICOLON + ) { + $spaces = $tokens[($semicolon + 1)]['length']; + if ($tokens[$semicolon]['line'] !== $tokens[$nextNonWhiteSpace]['line']) { + $spaces = 'newline'; + } + + if ($spaces !== 1 + && ($this->ignoreNewlines === false + || $spaces !== 'newline') + ) { + $error = 'Expected 1 space after %s semicolon of FOR loop; %s found'; + $errorCode = 'SpacingAfter'.$humanReadableCode; + $data[] = $spaces; + $fix = $phpcsFile->addFixableError($error, $semicolon, $errorCode, $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($semicolon + 1), ' '); + for ($i = ($semicolon + 2); $i < $nextNonWhiteSpace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + }//end if + } while ($semicolonCount < 2); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/InlineIfDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/InlineIfDeclarationSniff.php new file mode 100644 index 0000000..ff39c84 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/InlineIfDeclarationSniff.php @@ -0,0 +1,155 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class InlineIfDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INLINE_THEN]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $openBracket = null; + $closeBracket = null; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $parens = $tokens[$stackPtr]['nested_parenthesis']; + $openBracket = array_pop($parens); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + } + + // Find the beginning of the statement. If we don't find a + // semicolon (end of statement) or comma (end of array value) + // then assume the content before the closing parenthesis is the end. + $else = $phpcsFile->findNext(T_INLINE_ELSE, ($stackPtr + 1)); + $statementEnd = $phpcsFile->findNext([T_SEMICOLON, T_COMMA], ($else + 1), $closeBracket); + if ($statementEnd === false) { + $statementEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBracket - 1), null, true); + } + + // Make sure it's all on the same line. + if ($tokens[$statementEnd]['line'] !== $tokens[$stackPtr]['line']) { + $error = 'Inline shorthand IF statement must be declared on a single line'; + $phpcsFile->addError($error, $stackPtr, 'NotSingleLine'); + return; + } + + // Make sure there are spaces around the question mark. + $contentBefore = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + $contentAfter = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$contentBefore]['code'] !== T_CLOSE_PARENTHESIS) { + $error = 'Inline shorthand IF statement requires brackets around comparison'; + $phpcsFile->addError($error, $stackPtr, 'NoBrackets'); + } + + $spaceBefore = ($tokens[$stackPtr]['column'] - ($tokens[$contentBefore]['column'] + $tokens[$contentBefore]['length'])); + if ($spaceBefore !== 1) { + $error = 'Inline shorthand IF statement requires 1 space before THEN; %s found'; + $data = [$spaceBefore]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBeforeThen', $data); + if ($fix === true) { + if ($spaceBefore === 0) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } else { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + } + } + + // If there is no content between the ? and the : operators, then they are + // trying to replicate an elvis operator, even though PHP doesn't have one. + // In this case, we want no spaces between the two operators so ?: looks like + // an operator itself. + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_INLINE_ELSE) { + $inlineElse = $next; + if ($inlineElse !== ($stackPtr + 1)) { + $error = 'Inline shorthand IF statement without THEN statement requires 0 spaces between THEN and ELSE'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ElvisSpacing'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + } + } else { + $spaceAfter = (($tokens[$contentAfter]['column']) - ($tokens[$stackPtr]['column'] + 1)); + if ($spaceAfter !== 1) { + $error = 'Inline shorthand IF statement requires 1 space after THEN; %s found'; + $data = [$spaceAfter]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterThen', $data); + if ($fix === true) { + if ($spaceAfter === 0) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } else { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } + + // Make sure the ELSE has the correct spacing. + $inlineElse = $phpcsFile->findNext(T_INLINE_ELSE, ($stackPtr + 1), $statementEnd, false); + $contentBefore = $phpcsFile->findPrevious(T_WHITESPACE, ($inlineElse - 1), null, true); + $spaceBefore = ($tokens[$inlineElse]['column'] - ($tokens[$contentBefore]['column'] + $tokens[$contentBefore]['length'])); + if ($spaceBefore !== 1) { + $error = 'Inline shorthand IF statement requires 1 space before ELSE; %s found'; + $data = [$spaceBefore]; + $fix = $phpcsFile->addFixableError($error, $inlineElse, 'SpacingBeforeElse', $data); + if ($fix === true) { + if ($spaceBefore === 0) { + $phpcsFile->fixer->addContentBefore($inlineElse, ' '); + } else { + $phpcsFile->fixer->replaceToken(($inlineElse - 1), ' '); + } + } + } + }//end if + + $contentAfter = $phpcsFile->findNext(T_WHITESPACE, ($inlineElse + 1), null, true); + $spaceAfter = (($tokens[$contentAfter]['column']) - ($tokens[$inlineElse]['column'] + 1)); + if ($spaceAfter !== 1) { + $error = 'Inline shorthand IF statement requires 1 space after ELSE; %s found'; + $data = [$spaceAfter]; + $fix = $phpcsFile->addFixableError($error, $inlineElse, 'SpacingAfterElse', $data); + if ($fix === true) { + if ($spaceAfter === 0) { + $phpcsFile->fixer->addContent($inlineElse, ' '); + } else { + $phpcsFile->fixer->replaceToken(($inlineElse + 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/LowercaseDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/LowercaseDeclarationSniff.php new file mode 100644 index 0000000..068563c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/LowercaseDeclarationSniff.php @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class LowercaseDeclarationSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_ELSE, + T_ELSEIF, + T_FOREACH, + T_FOR, + T_DO, + T_SWITCH, + T_WHILE, + T_TRY, + T_CATCH, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $contentLc = strtolower($content); + if ($content !== $contentLc) { + $error = '%s keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + strtoupper($content), + $contentLc, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FoundUppercase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $contentLc); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php new file mode 100644 index 0000000..be46aed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php @@ -0,0 +1,304 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SwitchDeclarationSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * The number of spaces code should be indented. + * + * @var integer + */ + public $indent = 4; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_SWITCH]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // We can't process SWITCH statements unless we know where they start and end. + if (isset($tokens[$stackPtr]['scope_opener']) === false + || isset($tokens[$stackPtr]['scope_closer']) === false + ) { + return; + } + + $switch = $tokens[$stackPtr]; + $nextCase = $stackPtr; + $caseAlignment = ($switch['column'] + $this->indent); + $caseCount = 0; + $foundDefault = false; + + while (($nextCase = $phpcsFile->findNext([T_CASE, T_DEFAULT, T_SWITCH], ($nextCase + 1), $switch['scope_closer'])) !== false) { + // Skip nested SWITCH statements; they are handled on their own. + if ($tokens[$nextCase]['code'] === T_SWITCH) { + $nextCase = $tokens[$nextCase]['scope_closer']; + continue; + } + + if ($tokens[$nextCase]['code'] === T_DEFAULT) { + $type = 'Default'; + $foundDefault = true; + } else { + $type = 'Case'; + $caseCount++; + } + + if ($tokens[$nextCase]['content'] !== strtolower($tokens[$nextCase]['content'])) { + $expected = strtolower($tokens[$nextCase]['content']); + $error = strtoupper($type).' keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + $expected, + $tokens[$nextCase]['content'], + ]; + + $fix = $phpcsFile->addFixableError($error, $nextCase, $type.'NotLower', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($nextCase, $expected); + } + } + + if ($tokens[$nextCase]['column'] !== $caseAlignment) { + $error = strtoupper($type).' keyword must be indented '.$this->indent.' spaces from SWITCH keyword'; + $fix = $phpcsFile->addFixableError($error, $nextCase, $type.'Indent'); + + if ($fix === true) { + $padding = str_repeat(' ', ($caseAlignment - 1)); + if ($tokens[$nextCase]['column'] === 1 + || $tokens[($nextCase - 1)]['code'] !== T_WHITESPACE + ) { + $phpcsFile->fixer->addContentBefore($nextCase, $padding); + } else { + $phpcsFile->fixer->replaceToken(($nextCase - 1), $padding); + } + } + } + + if ($type === 'Case' + && ($tokens[($nextCase + 1)]['type'] !== 'T_WHITESPACE' + || $tokens[($nextCase + 1)]['content'] !== ' ') + ) { + $error = 'CASE keyword must be followed by a single space'; + $fix = $phpcsFile->addFixableError($error, $nextCase, 'SpacingAfterCase'); + if ($fix === true) { + if ($tokens[($nextCase + 1)]['type'] !== 'T_WHITESPACE') { + $phpcsFile->fixer->addContent($nextCase, ' '); + } else { + $phpcsFile->fixer->replaceToken(($nextCase + 1), ' '); + } + } + } + + if (isset($tokens[$nextCase]['scope_opener']) === false) { + $error = 'Possible parse error: CASE missing opening colon'; + $phpcsFile->addWarning($error, $nextCase, 'MissingColon'); + continue; + } + + $opener = $tokens[$nextCase]['scope_opener']; + if ($tokens[($opener - 1)]['type'] === 'T_WHITESPACE') { + $error = 'There must be no space before the colon in a '.strtoupper($type).' statement'; + $fix = $phpcsFile->addFixableError($error, $nextCase, 'SpaceBeforeColon'.$type); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($opener - 1), ''); + } + } + + $nextBreak = $tokens[$nextCase]['scope_closer']; + if ($tokens[$nextBreak]['code'] === T_BREAK + || $tokens[$nextBreak]['code'] === T_RETURN + || $tokens[$nextBreak]['code'] === T_CONTINUE + || $tokens[$nextBreak]['code'] === T_THROW + || $tokens[$nextBreak]['code'] === T_EXIT + ) { + if ($tokens[$nextBreak]['scope_condition'] === $nextCase) { + // Only need to check a couple of things once, even if the + // break is shared between multiple case statements, or even + // the default case. + if ($tokens[$nextBreak]['column'] !== $caseAlignment) { + $error = 'Case breaking statement must be indented '.$this->indent.' spaces from SWITCH keyword'; + $fix = $phpcsFile->addFixableError($error, $nextBreak, 'BreakIndent'); + + if ($fix === true) { + $padding = str_repeat(' ', ($caseAlignment - 1)); + if ($tokens[$nextBreak]['column'] === 1 + || $tokens[($nextBreak - 1)]['code'] !== T_WHITESPACE + ) { + $phpcsFile->fixer->addContentBefore($nextBreak, $padding); + } else { + $phpcsFile->fixer->replaceToken(($nextBreak - 1), $padding); + } + } + } + + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($nextBreak - 1), $stackPtr, true); + if ($tokens[$prev]['line'] !== ($tokens[$nextBreak]['line'] - 1)) { + $error = 'Blank lines are not allowed before case breaking statements'; + $phpcsFile->addError($error, $nextBreak, 'SpacingBeforeBreak'); + } + + $nextLine = $tokens[$tokens[$stackPtr]['scope_closer']]['line']; + $semicolon = $phpcsFile->findEndOfStatement($nextBreak); + for ($i = ($semicolon + 1); $i < $tokens[$stackPtr]['scope_closer']; $i++) { + if ($tokens[$i]['type'] !== 'T_WHITESPACE') { + $nextLine = $tokens[$i]['line']; + break; + } + } + + if ($type === 'Case') { + // Ensure the BREAK statement is followed by + // a single blank line, or the end switch brace. + if ($nextLine !== ($tokens[$semicolon]['line'] + 2) && $i !== $tokens[$stackPtr]['scope_closer']) { + $error = 'Case breaking statements must be followed by a single blank line'; + $fix = $phpcsFile->addFixableError($error, $nextBreak, 'SpacingAfterBreak'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($semicolon + 1); $i <= $tokens[$stackPtr]['scope_closer']; $i++) { + if ($tokens[$i]['line'] === $nextLine) { + $phpcsFile->fixer->addNewlineBefore($i); + break; + } + + if ($tokens[$i]['line'] === $tokens[$semicolon]['line']) { + continue; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + } else { + // Ensure the BREAK statement is not followed by a blank line. + if ($nextLine !== ($tokens[$semicolon]['line'] + 1)) { + $error = 'Blank lines are not allowed after the DEFAULT case\'s breaking statement'; + $phpcsFile->addError($error, $nextBreak, 'SpacingAfterDefaultBreak'); + } + }//end if + + $caseLine = $tokens[$nextCase]['line']; + $nextLine = $tokens[$nextBreak]['line']; + for ($i = ($opener + 1); $i < $nextBreak; $i++) { + if ($tokens[$i]['type'] !== 'T_WHITESPACE') { + $nextLine = $tokens[$i]['line']; + break; + } + } + + if ($nextLine !== ($caseLine + 1)) { + $error = 'Blank lines are not allowed after '.strtoupper($type).' statements'; + $phpcsFile->addError($error, $nextCase, 'SpacingAfter'.$type); + } + }//end if + + if ($tokens[$nextBreak]['code'] === T_BREAK) { + if ($type === 'Case') { + // Ensure empty CASE statements are not allowed. + // They must have some code content in them. A comment is not enough. + // But count RETURN statements as valid content if they also + // happen to close the CASE statement. + $foundContent = false; + for ($i = ($tokens[$nextCase]['scope_opener'] + 1); $i < $nextBreak; $i++) { + if ($tokens[$i]['code'] === T_CASE) { + $i = $tokens[$i]['scope_opener']; + continue; + } + + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === false) { + $foundContent = true; + break; + } + } + + if ($foundContent === false) { + $error = 'Empty CASE statements are not allowed'; + $phpcsFile->addError($error, $nextCase, 'EmptyCase'); + } + } else { + // Ensure empty DEFAULT statements are not allowed. + // They must (at least) have a comment describing why + // the default case is being ignored. + $foundContent = false; + for ($i = ($tokens[$nextCase]['scope_opener'] + 1); $i < $nextBreak; $i++) { + if ($tokens[$i]['type'] !== 'T_WHITESPACE') { + $foundContent = true; + break; + } + } + + if ($foundContent === false) { + $error = 'Comment required for empty DEFAULT case'; + $phpcsFile->addError($error, $nextCase, 'EmptyDefault'); + } + }//end if + }//end if + } else if ($type === 'Default') { + $error = 'DEFAULT case must have a breaking statement'; + $phpcsFile->addError($error, $nextCase, 'DefaultNoBreak'); + }//end if + }//end while + + if ($foundDefault === false) { + $error = 'All SWITCH statements must contain a DEFAULT case'; + $phpcsFile->addError($error, $stackPtr, 'MissingDefault'); + } + + if ($tokens[$switch['scope_closer']]['column'] !== $switch['column']) { + $error = 'Closing brace of SWITCH statement must be aligned with SWITCH keyword'; + $phpcsFile->addError($error, $switch['scope_closer'], 'CloseBraceAlign'); + } + + if ($caseCount === 0) { + $error = 'SWITCH statements must contain at least one CASE statement'; + $phpcsFile->addError($error, $stackPtr, 'MissingCase'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JSLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JSLintSniff.php new file mode 100644 index 0000000..012a6a3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JSLintSniff.php @@ -0,0 +1,86 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class JSLintSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jslint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $rhinoPath = Config::getExecutablePath('rhino'); + $jslintPath = Config::getExecutablePath('jslint'); + if ($rhinoPath === null || $jslintPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + + $rhinoPath = Common::escapeshellcmd($rhinoPath); + $jslintPath = Common::escapeshellcmd($jslintPath); + + $cmd = "$rhinoPath \"$jslintPath\" ".escapeshellarg($fileName); + exec($cmd, $output, $retval); + + if (is_array($output) === true) { + foreach ($output as $finding) { + $matches = []; + $numMatches = preg_match('/Lint at line ([0-9]+).*:(.*)$/', $finding, $matches); + if ($numMatches === 0) { + continue; + } + + $line = (int) $matches[1]; + $message = 'jslint says: '.trim($matches[2]); + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JavaScriptLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JavaScriptLintSniff.php new file mode 100644 index 0000000..e055cc1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JavaScriptLintSniff.php @@ -0,0 +1,89 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; + +class JavaScriptLintSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If Javascript Lint ran into trouble. + */ + public function process(File $phpcsFile, $stackPtr) + { + $jslPath = Config::getExecutablePath('jsl'); + if ($jslPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + + $cmd = '"'.Common::escapeshellcmd($jslPath).'" -nologo -nofilelisting -nocontext -nosummary -output-format __LINE__:__ERROR__ -process '.escapeshellarg($fileName); + $msg = exec($cmd, $output, $retval); + + // Variable $exitCode is the last line of $output if no error occurs, on + // error it is numeric. Try to handle various error conditions and + // provide useful error reporting. + if ($retval === 2 || $retval === 4) { + if (is_array($output) === true) { + $msg = join('\n', $output); + } + + throw new RuntimeException("Failed invoking JavaScript Lint, retval was [$retval], output was [$msg]"); + } + + if (is_array($output) === true) { + foreach ($output as $finding) { + $split = strpos($finding, ':'); + $line = substr($finding, 0, $split); + $message = substr($finding, ($split + 1)); + $phpcsFile->addWarningOnLine(trim($message), $line, 'ExternalTool'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Files/FileExtensionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Files/FileExtensionSniff.php new file mode 100644 index 0000000..4ba28a3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Files/FileExtensionSniff.php @@ -0,0 +1,68 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FileExtensionSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $fileName = $phpcsFile->getFilename(); + $extension = substr($fileName, strrpos($fileName, '.')); + $nextClass = $phpcsFile->findNext([T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], $stackPtr); + + if ($nextClass !== false) { + $phpcsFile->recordMetric($stackPtr, 'File extension for class files', $extension); + if ($extension === '.php') { + $error = '%s found in ".php" file; use ".inc" extension instead'; + $data = [ucfirst($tokens[$nextClass]['content'])]; + $phpcsFile->addError($error, $stackPtr, 'ClassFound', $data); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'File extension for non-class files', $extension); + if ($extension === '.inc') { + $error = 'No interface or class found in ".inc" file; use ".php" extension instead'; + $phpcsFile->addError($error, $stackPtr, 'NoClass'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php new file mode 100644 index 0000000..b79e6b3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php @@ -0,0 +1,395 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OperatorBracketSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$operators; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($phpcsFile->tokenizerType === 'JS' && $tokens[$stackPtr]['code'] === T_PLUS) { + // JavaScript uses the plus operator for string concatenation as well + // so we cannot accurately determine if it is a string concat or addition. + // So just ignore it. + return; + } + + // If the & is a reference, then we don't want to check for brackets. + if ($tokens[$stackPtr]['code'] === T_BITWISE_AND && $phpcsFile->isReference($stackPtr) === true) { + return; + } + + // There is one instance where brackets aren't needed, which involves + // the minus sign being used to assign a negative number to a variable. + if ($tokens[$stackPtr]['code'] === T_MINUS) { + // Check to see if we are trying to return -n. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] === T_RETURN) { + return; + } + + $number = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$number]['code'] === T_LNUMBER || $tokens[$number]['code'] === T_DNUMBER) { + $previous = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($previous !== false) { + $isAssignment = isset(Tokens::$assignmentTokens[$tokens[$previous]['code']]); + $isEquality = isset(Tokens::$equalityTokens[$tokens[$previous]['code']]); + $isComparison = isset(Tokens::$comparisonTokens[$tokens[$previous]['code']]); + $isUnary = isset(Tokens::$operators[$tokens[$previous]['code']]); + if ($isAssignment === true || $isEquality === true || $isComparison === true || $isUnary === true) { + // This is a negative assignment or comparison. + // We need to check that the minus and the number are + // adjacent. + if (($number - $stackPtr) !== 1) { + $error = 'No space allowed between minus sign and number'; + $phpcsFile->addError($error, $stackPtr, 'SpacingAfterMinus'); + } + + return; + } + } + } + }//end if + + $previousToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true, null, true); + if ($previousToken !== false) { + // A list of tokens that indicate that the token is not + // part of an arithmetic operation. + $invalidTokens = [ + T_COMMA => true, + T_COLON => true, + T_OPEN_PARENTHESIS => true, + T_OPEN_SQUARE_BRACKET => true, + T_OPEN_CURLY_BRACKET => true, + T_OPEN_SHORT_ARRAY => true, + T_CASE => true, + T_EXIT => true, + T_MATCH_ARROW => true, + ]; + + if (isset($invalidTokens[$tokens[$previousToken]['code']]) === true) { + return; + } + } + + if ($tokens[$stackPtr]['code'] === T_BITWISE_OR + && isset($tokens[$stackPtr]['nested_parenthesis']) === true + ) { + $brackets = $tokens[$stackPtr]['nested_parenthesis']; + $lastBracket = array_pop($brackets); + if (isset($tokens[$lastBracket]['parenthesis_owner']) === true + && $tokens[$tokens[$lastBracket]['parenthesis_owner']]['code'] === T_CATCH + ) { + // This is a pipe character inside a catch statement, so it is acting + // as an exception type separator and not an arithmetic operation. + return; + } + } + + // Tokens that are allowed inside a bracketed operation. + $allowed = [ + T_VARIABLE, + T_LNUMBER, + T_DNUMBER, + T_STRING, + T_WHITESPACE, + T_NS_SEPARATOR, + T_THIS, + T_SELF, + T_STATIC, + T_PARENT, + T_OBJECT_OPERATOR, + T_NULLSAFE_OBJECT_OPERATOR, + T_DOUBLE_COLON, + T_OPEN_SQUARE_BRACKET, + T_CLOSE_SQUARE_BRACKET, + T_MODULUS, + T_NONE, + T_BITWISE_NOT, + ]; + + $allowed += Tokens::$operators; + + $lastBracket = false; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $parenthesis = array_reverse($tokens[$stackPtr]['nested_parenthesis'], true); + foreach ($parenthesis as $bracket => $endBracket) { + $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($bracket - 1), null, true); + $prevCode = $tokens[$prevToken]['code']; + + if ($prevCode === T_ISSET) { + // This operation is inside an isset() call, but has + // no bracket of it's own. + break; + } + + if ($prevCode === T_STRING || $prevCode === T_SWITCH || $prevCode === T_MATCH) { + // We allow simple operations to not be bracketed. + // For example, ceil($one / $two). + for ($prev = ($stackPtr - 1); $prev > $bracket; $prev--) { + if (in_array($tokens[$prev]['code'], $allowed, true) === true) { + continue; + } + + if ($tokens[$prev]['code'] === T_CLOSE_PARENTHESIS) { + $prev = $tokens[$prev]['parenthesis_opener']; + } else { + break; + } + } + + if ($prev !== $bracket) { + break; + } + + for ($next = ($stackPtr + 1); $next < $endBracket; $next++) { + if (in_array($tokens[$next]['code'], $allowed, true) === true) { + continue; + } + + if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { + $next = $tokens[$next]['parenthesis_closer']; + } else { + break; + } + } + + if ($next !== $endBracket) { + break; + } + }//end if + + if (in_array($prevCode, Tokens::$scopeOpeners, true) === true) { + // This operation is inside a control structure like FOREACH + // or IF, but has no bracket of it's own. + // The only control structures allowed to do this are SWITCH and MATCH. + if ($prevCode !== T_SWITCH && $prevCode !== T_MATCH) { + break; + } + } + + if ($prevCode === T_OPEN_PARENTHESIS) { + // These are two open parenthesis in a row. If the current + // one doesn't enclose the operator, go to the previous one. + if ($endBracket < $stackPtr) { + continue; + } + } + + $lastBracket = $bracket; + break; + }//end foreach + }//end if + + if ($lastBracket === false) { + // It is not in a bracketed statement at all. + $this->addMissingBracketsError($phpcsFile, $stackPtr); + return; + } else if ($tokens[$lastBracket]['parenthesis_closer'] < $stackPtr) { + // There are a set of brackets in front of it that don't include it. + $this->addMissingBracketsError($phpcsFile, $stackPtr); + return; + } else { + // We are enclosed in a set of bracket, so the last thing to + // check is that we are not also enclosed in square brackets + // like this: ($array[$index + 1]), which is invalid. + $brackets = [ + T_OPEN_SQUARE_BRACKET, + T_CLOSE_SQUARE_BRACKET, + ]; + + $squareBracket = $phpcsFile->findPrevious($brackets, ($stackPtr - 1), $lastBracket); + if ($squareBracket !== false && $tokens[$squareBracket]['code'] === T_OPEN_SQUARE_BRACKET) { + $closeSquareBracket = $phpcsFile->findNext($brackets, ($stackPtr + 1)); + if ($closeSquareBracket !== false && $tokens[$closeSquareBracket]['code'] === T_CLOSE_SQUARE_BRACKET) { + $this->addMissingBracketsError($phpcsFile, $stackPtr); + } + } + + return; + }//end if + + $lastAssignment = $phpcsFile->findPrevious(Tokens::$assignmentTokens, $stackPtr, null, false, null, true); + if ($lastAssignment !== false && $lastAssignment > $lastBracket) { + $this->addMissingBracketsError($phpcsFile, $stackPtr); + } + + }//end process() + + + /** + * Add and fix the missing brackets error. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function addMissingBracketsError($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $allowed = [ + T_VARIABLE => true, + T_LNUMBER => true, + T_DNUMBER => true, + T_STRING => true, + T_CONSTANT_ENCAPSED_STRING => true, + T_DOUBLE_QUOTED_STRING => true, + T_WHITESPACE => true, + T_NS_SEPARATOR => true, + T_THIS => true, + T_SELF => true, + T_STATIC => true, + T_OBJECT_OPERATOR => true, + T_NULLSAFE_OBJECT_OPERATOR => true, + T_DOUBLE_COLON => true, + T_MODULUS => true, + T_ISSET => true, + T_ARRAY => true, + T_NONE => true, + T_BITWISE_NOT => true, + ]; + + // Find the first token in the expression. + for ($before = ($stackPtr - 1); $before > 0; $before--) { + // Special case for plus operators because we can't tell if they are used + // for addition or string contact. So assume string concat to be safe. + if ($phpcsFile->tokenizerType === 'JS' && $tokens[$before]['code'] === T_PLUS) { + break; + } + + if (isset(Tokens::$emptyTokens[$tokens[$before]['code']]) === true + || isset(Tokens::$operators[$tokens[$before]['code']]) === true + || isset(Tokens::$castTokens[$tokens[$before]['code']]) === true + || isset($allowed[$tokens[$before]['code']]) === true + ) { + continue; + } + + if ($tokens[$before]['code'] === T_CLOSE_PARENTHESIS) { + $before = $tokens[$before]['parenthesis_opener']; + continue; + } + + if ($tokens[$before]['code'] === T_CLOSE_SQUARE_BRACKET) { + $before = $tokens[$before]['bracket_opener']; + continue; + } + + if ($tokens[$before]['code'] === T_CLOSE_SHORT_ARRAY) { + $before = $tokens[$before]['bracket_opener']; + continue; + } + + break; + }//end for + + $before = $phpcsFile->findNext(Tokens::$emptyTokens, ($before + 1), null, true); + + // A few extra tokens are allowed to be on the right side of the expression. + $allowed[T_EQUAL] = true; + $allowed[T_NEW] = true; + + // Find the last token in the expression. + for ($after = ($stackPtr + 1); $after < $phpcsFile->numTokens; $after++) { + // Special case for plus operators because we can't tell if they are used + // for addition or string concat. So assume string concat to be safe. + if ($phpcsFile->tokenizerType === 'JS' && $tokens[$after]['code'] === T_PLUS) { + break; + } + + if (isset(Tokens::$emptyTokens[$tokens[$after]['code']]) === true + || isset(Tokens::$operators[$tokens[$after]['code']]) === true + || isset(Tokens::$castTokens[$tokens[$after]['code']]) === true + || isset($allowed[$tokens[$after]['code']]) === true + ) { + continue; + } + + if ($tokens[$after]['code'] === T_OPEN_PARENTHESIS) { + $after = $tokens[$after]['parenthesis_closer']; + continue; + } + + if ($tokens[$after]['code'] === T_OPEN_SQUARE_BRACKET) { + $after = $tokens[$after]['bracket_closer']; + continue; + } + + if ($tokens[$after]['code'] === T_OPEN_SHORT_ARRAY) { + $after = $tokens[$after]['bracket_closer']; + continue; + } + + break; + }//end for + + $after = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($after - 1), null, true); + + $error = 'Operation must be bracketed'; + if ($before === $after || $before === $stackPtr || $after === $stackPtr) { + $phpcsFile->addError($error, $stackPtr, 'MissingBrackets'); + return; + } + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'MissingBrackets'); + if ($fix === true) { + // Can only fix this error if both tokens are available for fixing. + // Adding one bracket without the other will create parse errors. + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($before, '('.$tokens[$before]['content']); + $phpcsFile->fixer->replaceToken($after, $tokens[$after]['content'].')'); + $phpcsFile->fixer->endChangeset(); + } + + }//end addMissingBracketsError() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php new file mode 100644 index 0000000..7357a50 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php @@ -0,0 +1,398 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionDeclarationArgumentSpacingSniff implements Sniff +{ + + /** + * How many spaces should surround the equals signs. + * + * @var integer + */ + public $equalsSpacing = 0; + + /** + * How many spaces should follow the opening bracket. + * + * @var integer + */ + public $requiredSpacesAfterOpen = 0; + + /** + * How many spaces should precede the closing bracket. + * + * @var integer + */ + public $requiredSpacesBeforeClose = 0; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + T_FN, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false + || isset($tokens[$stackPtr]['parenthesis_closer']) === false + || $tokens[$stackPtr]['parenthesis_opener'] === null + || $tokens[$stackPtr]['parenthesis_closer'] === null + ) { + return; + } + + $this->equalsSpacing = (int) $this->equalsSpacing; + $this->requiredSpacesAfterOpen = (int) $this->requiredSpacesAfterOpen; + $this->requiredSpacesBeforeClose = (int) $this->requiredSpacesBeforeClose; + + $this->processBracket($phpcsFile, $tokens[$stackPtr]['parenthesis_opener']); + + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1), null); + $this->processBracket($phpcsFile, $openBracket); + } + } + + }//end process() + + + /** + * Processes the contents of a single set of brackets. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $openBracket The position of the open bracket + * in the stack. + * + * @return void + */ + public function processBracket($phpcsFile, $openBracket) + { + $tokens = $phpcsFile->getTokens(); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + $multiLine = ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']); + + if (isset($tokens[$openBracket]['parenthesis_owner']) === true) { + $stackPtr = $tokens[$openBracket]['parenthesis_owner']; + } else { + $stackPtr = $phpcsFile->findPrevious(T_USE, ($openBracket - 1)); + } + + $params = $phpcsFile->getMethodParameters($stackPtr); + + if (empty($params) === true) { + // Check spacing around parenthesis. + $next = $phpcsFile->findNext(T_WHITESPACE, ($openBracket + 1), $closeBracket, true); + if ($next === false) { + if (($closeBracket - $openBracket) !== 1) { + if ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($openBracket + 1)]['length']; + } + + $error = 'Expected 0 spaces between parenthesis of function declaration; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $openBracket, 'SpacingBetween', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($openBracket + 1), ''); + } + } + + // No params, so we don't check normal spacing rules. + return; + } + }//end if + + foreach ($params as $paramNumber => $param) { + if ($param['pass_by_reference'] === true) { + $refToken = $param['reference_token']; + + $gap = 0; + if ($tokens[($refToken + 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($refToken + 1)]['length']; + } + + if ($gap !== 0) { + $error = 'Expected 0 spaces after reference operator for argument "%s"; %s found'; + $data = [ + $param['name'], + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $refToken, 'SpacingAfterReference', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($refToken + 1), ''); + } + } + }//end if + + if ($param['variable_length'] === true) { + $variadicToken = $param['variadic_token']; + + $gap = 0; + if ($tokens[($variadicToken + 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($variadicToken + 1)]['length']; + } + + if ($gap !== 0) { + $error = 'Expected 0 spaces after variadic operator for argument "%s"; %s found'; + $data = [ + $param['name'], + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $variadicToken, 'SpacingAfterVariadic', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($variadicToken + 1), ''); + } + } + }//end if + + if (isset($param['default_equal_token']) === true) { + $equalToken = $param['default_equal_token']; + + $spacesBefore = 0; + if (($equalToken - $param['token']) > 1) { + $spacesBefore = $tokens[($param['token'] + 1)]['length']; + } + + if ($spacesBefore !== $this->equalsSpacing) { + $error = 'Incorrect spacing between argument "%s" and equals sign; expected '.$this->equalsSpacing.' but found %s'; + $data = [ + $param['name'], + $spacesBefore, + ]; + + $fix = $phpcsFile->addFixableError($error, $equalToken, 'SpaceBeforeEquals', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->equalsSpacing); + if ($spacesBefore === 0) { + $phpcsFile->fixer->addContentBefore($equalToken, $padding); + } else { + $phpcsFile->fixer->replaceToken(($equalToken - 1), $padding); + } + } + }//end if + + $spacesAfter = 0; + if ($tokens[($equalToken + 1)]['code'] === T_WHITESPACE) { + $spacesAfter = $tokens[($equalToken + 1)]['length']; + } + + if ($spacesAfter !== $this->equalsSpacing) { + $error = 'Incorrect spacing between default value and equals sign for argument "%s"; expected '.$this->equalsSpacing.' but found %s'; + $data = [ + $param['name'], + $spacesAfter, + ]; + + $fix = $phpcsFile->addFixableError($error, $equalToken, 'SpaceAfterEquals', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->equalsSpacing); + if ($spacesAfter === 0) { + $phpcsFile->fixer->addContent($equalToken, $padding); + } else { + $phpcsFile->fixer->replaceToken(($equalToken + 1), $padding); + } + } + }//end if + }//end if + + if ($param['type_hint_token'] !== false) { + $typeHintToken = $param['type_hint_end_token']; + + $gap = 0; + if ($tokens[($typeHintToken + 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($typeHintToken + 1)]['length']; + } + + if ($gap !== 1) { + $error = 'Expected 1 space between type hint and argument "%s"; %s found'; + $data = [ + $param['name'], + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $typeHintToken, 'SpacingAfterHint', $data); + if ($fix === true) { + if ($gap === 0) { + $phpcsFile->fixer->addContent($typeHintToken, ' '); + } else { + $phpcsFile->fixer->replaceToken(($typeHintToken + 1), ' '); + } + } + } + }//end if + + $commaToken = false; + if ($paramNumber > 0 && $params[($paramNumber - 1)]['comma_token'] !== false) { + $commaToken = $params[($paramNumber - 1)]['comma_token']; + } + + if ($commaToken !== false) { + if ($tokens[($commaToken - 1)]['code'] === T_WHITESPACE) { + $error = 'Expected 0 spaces between argument "%s" and comma; %s found'; + $data = [ + $params[($paramNumber - 1)]['name'], + $tokens[($commaToken - 1)]['length'], + ]; + + $fix = $phpcsFile->addFixableError($error, $commaToken, 'SpaceBeforeComma', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($commaToken - 1), ''); + } + } + + // Don't check spacing after the comma if it is the last content on the line. + $checkComma = true; + if ($multiLine === true) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($commaToken + 1), $closeBracket, true); + if ($tokens[$next]['line'] !== $tokens[$commaToken]['line']) { + $checkComma = false; + } + } + + if ($checkComma === true) { + if ($param['type_hint_token'] === false) { + $spacesAfter = 0; + if ($tokens[($commaToken + 1)]['code'] === T_WHITESPACE) { + $spacesAfter = $tokens[($commaToken + 1)]['length']; + } + + if ($spacesAfter === 0) { + $error = 'Expected 1 space between comma and argument "%s"; 0 found'; + $data = [$param['name']]; + $fix = $phpcsFile->addFixableError($error, $commaToken, 'NoSpaceBeforeArg', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($commaToken, ' '); + } + } else if ($spacesAfter !== 1) { + $error = 'Expected 1 space between comma and argument "%s"; %s found'; + $data = [ + $param['name'], + $spacesAfter, + ]; + + $fix = $phpcsFile->addFixableError($error, $commaToken, 'SpacingBeforeArg', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($commaToken + 1), ' '); + } + }//end if + } else { + $hint = $phpcsFile->getTokensAsString($param['type_hint_token'], (($param['type_hint_end_token'] - $param['type_hint_token']) + 1)); + if ($param['nullable_type'] === true) { + $hint = '?'.$hint; + } + + if ($tokens[($commaToken + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space between comma and type hint "%s"; 0 found'; + $data = [$hint]; + $fix = $phpcsFile->addFixableError($error, $commaToken, 'NoSpaceBeforeHint', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($commaToken, ' '); + } + } else { + $gap = $tokens[($commaToken + 1)]['length']; + if ($gap !== 1) { + $error = 'Expected 1 space between comma and type hint "%s"; %s found'; + $data = [ + $hint, + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $commaToken, 'SpacingBeforeHint', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($commaToken + 1), ' '); + } + } + }//end if + }//end if + }//end if + }//end if + }//end foreach + + // Only check spacing around parenthesis for single line definitions. + if ($multiLine === true) { + return; + } + + $gap = 0; + if ($tokens[($closeBracket - 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($closeBracket - 1)]['length']; + } + + if ($gap !== $this->requiredSpacesBeforeClose) { + $error = 'Expected %s spaces before closing parenthesis; %s found'; + $data = [ + $this->requiredSpacesBeforeClose, + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'SpacingBeforeClose', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesBeforeClose); + if ($gap === 0) { + $phpcsFile->fixer->addContentBefore($closeBracket, $padding); + } else { + $phpcsFile->fixer->replaceToken(($closeBracket - 1), $padding); + } + } + } + + $gap = 0; + if ($tokens[($openBracket + 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($openBracket + 1)]['length']; + } + + if ($gap !== $this->requiredSpacesAfterOpen) { + $error = 'Expected %s spaces after opening parenthesis; %s found'; + $data = [ + $this->requiredSpacesAfterOpen, + $gap, + ]; + $fix = $phpcsFile->addFixableError($error, $openBracket, 'SpacingAfterOpen', $data); + if ($fix === true) { + $padding = str_repeat(' ', $this->requiredSpacesAfterOpen); + if ($gap === 0) { + $phpcsFile->fixer->addContent($openBracket, $padding); + } else { + $phpcsFile->fixer->replaceToken(($openBracket + 1), $padding); + } + } + } + + }//end processBracket() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationSniff.php new file mode 100644 index 0000000..fdb391c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationSniff.php @@ -0,0 +1,34 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Sniffs\AbstractPatternSniff; + +class FunctionDeclarationSniff extends AbstractPatternSniff +{ + + + /** + * Returns an array of patterns to check are correct. + * + * @return array + */ + protected function getPatterns() + { + return [ + 'function abc(...);', + 'function abc(...)', + 'abstract function abc(...);', + ]; + + }//end getPatterns() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDuplicateArgumentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDuplicateArgumentSniff.php new file mode 100644 index 0000000..5eafbfd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDuplicateArgumentSniff.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FunctionDuplicateArgumentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + + $foundVariables = []; + for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { + if ($tokens[$i]['code'] === T_VARIABLE) { + $variable = $tokens[$i]['content']; + if (in_array($variable, $foundVariables, true) === true) { + $error = 'Variable "%s" appears more than once in function declaration'; + $data = [$variable]; + $phpcsFile->addError($error, $i, 'Found', $data); + } else { + $foundVariables[] = $variable; + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/GlobalFunctionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/GlobalFunctionSniff.php new file mode 100644 index 0000000..af3d902 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/GlobalFunctionSniff.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class GlobalFunctionSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (empty($tokens[$stackPtr]['conditions']) === true) { + $functionName = $phpcsFile->getDeclarationName($stackPtr); + if ($functionName === null) { + return; + } + + // Special exception for __autoload as it needs to be global. + if ($functionName !== '__autoload') { + $error = 'Consider putting global function "%s" in a static class'; + $data = [$functionName]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/LowercaseFunctionKeywordsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/LowercaseFunctionKeywordsSniff.php new file mode 100644 index 0000000..401b840 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/LowercaseFunctionKeywordsSniff.php @@ -0,0 +1,69 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class LowercaseFunctionKeywordsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $tokens = Tokens::$methodPrefixes; + $tokens[] = T_FUNCTION; + $tokens[] = T_CLOSURE; + $tokens[] = T_FN; + + return $tokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $contentLc = strtolower($content); + if ($content !== $contentLc) { + $error = '%s keyword must be lowercase; expected "%s" but found "%s"'; + $data = [ + strtoupper($content), + $contentLc, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FoundUppercase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $contentLc); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php new file mode 100644 index 0000000..626b330 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php @@ -0,0 +1,258 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions; + +use PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionDeclarationSniff as PEARFunctionDeclarationSniff; +use PHP_CodeSniffer\Util\Tokens; + +class MultiLineFunctionDeclarationSniff extends PEARFunctionDeclarationSniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Determine if this is a multi-line function declaration. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return bool + */ + public function isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) + { + $bracketsToCheck = [$stackPtr => $openBracket]; + + // Closures may use the USE keyword and so be multi-line in this way. + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + $use = $phpcsFile->findNext(T_USE, ($tokens[$openBracket]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']); + if ($use !== false) { + $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); + if ($open !== false) { + $bracketsToCheck[$use] = $open; + } + } + } + + foreach ($bracketsToCheck as $stackPtr => $openBracket) { + // If the first argument is on a new line, this is a multi-line + // function declaration, even if there is only one argument. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + return true; + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + $end = $phpcsFile->findEndOfStatement($openBracket + 1); + while ($tokens[$end]['code'] === T_COMMA) { + // If the next bit of code is not on the same line, this is a + // multi-line function declaration. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); + if ($next === false) { + continue(2); + } + + if ($tokens[$next]['line'] !== $tokens[$end]['line']) { + return true; + } + + $end = $phpcsFile->findEndOfStatement($next); + } + + // We've reached the last argument, so see if the next content + // (should be the close bracket) is also on the same line. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); + if ($next !== false && $tokens[$next]['line'] !== $tokens[$end]['line']) { + return true; + } + }//end foreach + + return false; + + }//end isMultiLineDeclaration() + + + /** + * Processes single-line declarations. + * + * Just uses the Generic BSD-Allman brace sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens) + { + // We do everything the parent sniff does, and a bit more because we + // define multi-line declarations a bit differently. + parent::processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens); + + $openingBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closingBracket = $tokens[$stackPtr]['parenthesis_closer']; + + $prevNonWhiteSpace = $phpcsFile->findPrevious(T_WHITESPACE, ($closingBracket - 1), $openingBracket, true); + if ($tokens[$prevNonWhiteSpace]['line'] !== $tokens[$closingBracket]['line']) { + $error = 'There must not be a newline before the closing parenthesis of a single-line function declaration'; + + if (isset(Tokens::$emptyTokens[$tokens[$prevNonWhiteSpace]['code']]) === true) { + $phpcsFile->addError($error, $closingBracket, 'CloseBracketNewLine'); + } else { + $fix = $phpcsFile->addFixableError($error, $closingBracket, 'CloseBracketNewLine'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($closingBracket - 1); $i > $openingBracket; $i--) { + if ($tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + + }//end processSingleLineDeclaration() + + + /** + * Processes multi-line declarations. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * + * @return void + */ + public function processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens) + { + // We do everything the parent sniff does, and a bit more. + parent::processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens); + + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $this->processBracket($phpcsFile, $openBracket, $tokens, 'function'); + + if ($tokens[$stackPtr]['code'] !== T_CLOSURE) { + return; + } + + $use = $phpcsFile->findNext(T_USE, ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']); + if ($use === false) { + return; + } + + $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1), null); + $this->processBracket($phpcsFile, $openBracket, $tokens, 'use'); + + }//end processMultiLineDeclaration() + + + /** + * Processes the contents of a single set of brackets. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $openBracket The position of the open bracket + * in the stack passed in $tokens. + * @param array $tokens The stack of tokens that make up + * the file. + * @param string $type The type of the token the brackets + * belong to (function or use). + * + * @return void + */ + public function processBracket($phpcsFile, $openBracket, $tokens, $type='function') + { + $errorPrefix = ''; + if ($type === 'use') { + $errorPrefix = 'Use'; + } + + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + + // The open bracket should be the last thing on the line. + if ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$openBracket]['line']) { + $error = 'The first parameter of a multi-line '.$type.' declaration must be on the line after the opening bracket'; + $fix = $phpcsFile->addFixableError($error, $next, $errorPrefix.'FirstParamSpacing'); + if ($fix === true) { + if ($tokens[$next]['line'] === $tokens[$openBracket]['line']) { + $phpcsFile->fixer->addNewline($openBracket); + } else { + $phpcsFile->fixer->beginChangeset(); + for ($x = $openBracket; $x < $next; $x++) { + if ($tokens[$x]['line'] === $tokens[$openBracket]['line']) { + continue; + } + + if ($tokens[$x]['line'] === $tokens[$next]['line']) { + break; + } + } + + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + }//end if + + // Each line between the brackets should contain a single parameter. + $lastComma = null; + for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { + // Skip brackets, like arrays, as they can contain commas. + if (isset($tokens[$i]['bracket_opener']) === true) { + $i = $tokens[$i]['bracket_closer']; + continue; + } + + if (isset($tokens[$i]['parenthesis_opener']) === true) { + $i = $tokens[$i]['parenthesis_closer']; + continue; + } + + if ($tokens[$i]['code'] !== T_COMMA) { + continue; + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), null, true); + if ($tokens[$next]['line'] === $tokens[$i]['line']) { + $error = 'Multi-line '.$type.' declarations must define one parameter per line'; + $fix = $phpcsFile->addFixableError($error, $next, $errorPrefix.'OneParamPerLine'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($i); + } + } + }//end for + + }//end processBracket() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php new file mode 100644 index 0000000..2450ba7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php @@ -0,0 +1,54 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Standards\PEAR\Sniffs\NamingConventions\ValidFunctionNameSniff as PEARValidFunctionNameSniff; +use PHP_CodeSniffer\Util\Common; + +class ValidFunctionNameSniff extends PEARValidFunctionNameSniff +{ + + + /** + * Processes the tokens outside the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $functionName = $phpcsFile->getDeclarationName($stackPtr); + if ($functionName === null) { + return; + } + + $errorData = [$functionName]; + + // Does this function claim to be magical? + if (preg_match('|^__[^_]|', $functionName) !== 0) { + $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'DoubleUnderscore', $errorData); + + $functionName = ltrim($functionName, '_'); + } + + if (Common::isCamelCaps($functionName, false, true, false) === false) { + $error = 'Function name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + } + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidVariableNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidVariableNameSniff.php new file mode 100644 index 0000000..79f9c4b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -0,0 +1,190 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Tokens; + +class ValidVariableNameSniff extends AbstractVariableSniff +{ + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $varName = ltrim($tokens[$stackPtr]['content'], '$'); + + // If it's a php reserved var, then its ok. + if (isset($this->phpReservedVars[$varName]) === true) { + return; + } + + $objOperator = $phpcsFile->findNext([T_WHITESPACE], ($stackPtr + 1), null, true); + if ($tokens[$objOperator]['code'] === T_OBJECT_OPERATOR + || $tokens[$objOperator]['code'] === T_NULLSAFE_OBJECT_OPERATOR + ) { + // Check to see if we are using a variable from an object. + $var = $phpcsFile->findNext([T_WHITESPACE], ($objOperator + 1), null, true); + if ($tokens[$var]['code'] === T_STRING) { + $bracket = $phpcsFile->findNext([T_WHITESPACE], ($var + 1), null, true); + if ($tokens[$bracket]['code'] !== T_OPEN_PARENTHESIS) { + $objVarName = $tokens[$var]['content']; + + // There is no way for us to know if the var is public or + // private, so we have to ignore a leading underscore if there is + // one and just check the main part of the variable name. + $originalVarName = $objVarName; + if (substr($objVarName, 0, 1) === '_') { + $objVarName = substr($objVarName, 1); + } + + if (Common::isCamelCaps($objVarName, false, true, false) === false) { + $error = 'Member variable "%s" is not in valid camel caps format'; + $data = [$originalVarName]; + $phpcsFile->addError($error, $var, 'MemberNotCamelCaps', $data); + } + }//end if + }//end if + }//end if + + $objOperator = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$objOperator]['code'] === T_DOUBLE_COLON) { + // The variable lives within a class, and is referenced like + // this: MyClass::$_variable, so we don't know its scope. + $objVarName = $varName; + if (substr($objVarName, 0, 1) === '_') { + $objVarName = substr($objVarName, 1); + } + + if (Common::isCamelCaps($objVarName, false, true, false) === false) { + $error = 'Member variable "%s" is not in valid camel caps format'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addError($error, $stackPtr, 'MemberNotCamelCaps', $data); + } + + return; + } + + // There is no way for us to know if the var is public or private, + // so we have to ignore a leading underscore if there is one and just + // check the main part of the variable name. + $originalVarName = $varName; + if (substr($varName, 0, 1) === '_') { + $inClass = $phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens); + if ($inClass === true) { + $varName = substr($varName, 1); + } + } + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Variable "%s" is not in valid camel caps format'; + $data = [$originalVarName]; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); + } + + }//end processVariable() + + + /** + * Processes class member variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $varName = ltrim($tokens[$stackPtr]['content'], '$'); + $memberProps = $phpcsFile->getMemberProperties($stackPtr); + if (empty($memberProps) === true) { + // Couldn't get any info about this variable, which + // generally means it is invalid or possibly has a parse + // error. Any errors will be reported by the core, so + // we can ignore it. + return; + } + + $public = ($memberProps['scope'] !== 'private'); + $errorData = [$varName]; + + if ($public === true) { + if (substr($varName, 0, 1) === '_') { + $error = '%s member variable "%s" must not contain a leading underscore'; + $data = [ + ucfirst($memberProps['scope']), + $errorData[0], + ]; + $phpcsFile->addError($error, $stackPtr, 'PublicHasUnderscore', $data); + } + } else { + if (substr($varName, 0, 1) !== '_') { + $error = 'Private member variable "%s" must contain a leading underscore'; + $phpcsFile->addError($error, $stackPtr, 'PrivateNoUnderscore', $errorData); + } + } + + // Remove a potential underscore prefix for testing CamelCaps. + $varName = ltrim($varName, '_'); + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Member variable "%s" is not in valid camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'MemberNotCamelCaps', $errorData); + } + + }//end processMemberVar() + + + /** + * Processes the variable found within a double quoted string. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the double quoted + * string. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (preg_match_all('|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[$stackPtr]['content'], $matches) !== 0) { + foreach ($matches[1] as $varName) { + // If it's a php reserved var, then its ok. + if (isset($this->phpReservedVars[$varName]) === true) { + continue; + } + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Variable "%s" is not in valid camel caps format'; + $data = [$varName]; + $phpcsFile->addError($error, $stackPtr, 'StringNotCamelCaps', $data); + } + } + } + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/DisallowObjectStringIndexSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/DisallowObjectStringIndexSniff.php new file mode 100644 index 0000000..7bd14eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/DisallowObjectStringIndexSniff.php @@ -0,0 +1,85 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowObjectStringIndexSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_SQUARE_BRACKET]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Check if the next non whitespace token is a string. + $index = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$index]['code'] !== T_CONSTANT_ENCAPSED_STRING) { + return; + } + + // Make sure it is the only thing in the square brackets. + $next = $phpcsFile->findNext(T_WHITESPACE, ($index + 1), null, true); + if ($tokens[$next]['code'] !== T_CLOSE_SQUARE_BRACKET) { + return; + } + + // Allow indexes that have dots in them because we can't write + // them in dot notation. + $content = trim($tokens[$index]['content'], '"\' '); + if (strpos($content, '.') !== false) { + return; + } + + // Also ignore reserved words. + if ($content === 'super') { + return; + } + + // Token before the opening square bracket cannot be a var name. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] === T_STRING) { + $error = 'Object indexes must be written in dot notation'; + $phpcsFile->addError($error, $prev, 'Found'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectInstantiationSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectInstantiationSniff.php new file mode 100644 index 0000000..d408a07 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectInstantiationSniff.php @@ -0,0 +1,85 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ObjectInstantiationSniff implements Sniff +{ + + + /** + * Registers the token types that this sniff wishes to listen to. + * + * @return array + */ + public function register() + { + return [T_NEW]; + + }//end register() + + + /** + * Process the tokens that this sniff is listening for. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $allowedTokens = Tokens::$emptyTokens; + $allowedTokens[] = T_BITWISE_AND; + + $prev = $phpcsFile->findPrevious($allowedTokens, ($stackPtr - 1), null, true); + + $allowedTokens = [ + T_EQUAL => T_EQUAL, + T_COALESCE_EQUAL => T_COALESCE_EQUAL, + T_DOUBLE_ARROW => T_DOUBLE_ARROW, + T_FN_ARROW => T_FN_ARROW, + T_MATCH_ARROW => T_MATCH_ARROW, + T_THROW => T_THROW, + T_RETURN => T_RETURN, + ]; + + if (isset($allowedTokens[$tokens[$prev]['code']]) === true) { + return; + } + + $ternaryLikeTokens = [ + T_COALESCE => true, + T_INLINE_THEN => true, + T_INLINE_ELSE => true, + ]; + + // For ternary like tokens, walk a little further back to see if it is preceded by + // one of the allowed tokens (within the same statement). + if (isset($ternaryLikeTokens[$tokens[$prev]['code']]) === true) { + $hasAllowedBefore = $phpcsFile->findPrevious($allowedTokens, ($prev - 1), null, false, null, true); + if ($hasAllowedBefore !== false) { + return; + } + } + + $error = 'New objects must be assigned to a variable'; + $phpcsFile->addError($error, $stackPtr, 'NotAssigned'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectMemberCommaSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectMemberCommaSniff.php new file mode 100644 index 0000000..04bd5d1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectMemberCommaSniff.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ObjectMemberCommaSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Registers the token types that this sniff wishes to listen to. + * + * @return array + */ + public function register() + { + return [T_CLOSE_OBJECT]; + + }//end register() + + + /** + * Process the tokens that this sniff is listening for. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] === T_COMMA) { + $error = 'Last member of object must not be followed by a comma'; + $fix = $phpcsFile->addFixableError($error, $prev, 'Found'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($prev, ''); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff.php new file mode 100644 index 0000000..e9b41d6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff.php @@ -0,0 +1,235 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ComparisonOperatorUsageSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * A list of valid comparison operators. + * + * @var array + */ + private static $validOps = [ + T_IS_IDENTICAL => true, + T_IS_NOT_IDENTICAL => true, + T_LESS_THAN => true, + T_GREATER_THAN => true, + T_IS_GREATER_OR_EQUAL => true, + T_IS_SMALLER_OR_EQUAL => true, + T_INSTANCEOF => true, + ]; + + /** + * A list of invalid operators with their alternatives. + * + * @var array> + */ + private static $invalidOps = [ + 'PHP' => [ + T_IS_EQUAL => '===', + T_IS_NOT_EQUAL => '!==', + T_BOOLEAN_NOT => '=== FALSE', + ], + 'JS' => [ + T_IS_EQUAL => '===', + T_IS_NOT_EQUAL => '!==', + ], + ]; + + + /** + * Registers the token types that this sniff wishes to listen to. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_ELSEIF, + T_INLINE_THEN, + T_WHILE, + T_FOR, + ]; + + }//end register() + + + /** + * Process the tokens that this sniff is listening for. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where the token + * was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $tokenizer = $phpcsFile->tokenizerType; + + if ($tokens[$stackPtr]['code'] === T_INLINE_THEN) { + $end = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$end]['code'] !== T_CLOSE_PARENTHESIS) { + // This inline IF statement does not have its condition + // bracketed, so we need to guess where it starts. + for ($i = ($end - 1); $i >= 0; $i--) { + if ($tokens[$i]['code'] === T_SEMICOLON) { + // Stop here as we assume it is the end + // of the previous statement. + break; + } else if ($tokens[$i]['code'] === T_OPEN_TAG) { + // Stop here as this is the start of the file. + break; + } else if ($tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET) { + // Stop if this is the closing brace of + // a code block. + if (isset($tokens[$i]['scope_opener']) === true) { + break; + } + } else if ($tokens[$i]['code'] === T_OPEN_CURLY_BRACKET) { + // Stop if this is the opening brace of + // a code block. + if (isset($tokens[$i]['scope_closer']) === true) { + break; + } + } else if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) { + // Stop if this is the start of a pair of + // parentheses that surrounds the inline + // IF statement. + if (isset($tokens[$i]['parenthesis_closer']) === true + && $tokens[$i]['parenthesis_closer'] >= $stackPtr + ) { + break; + } + }//end if + }//end for + + $start = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), null, true); + } else { + if (isset($tokens[$end]['parenthesis_opener']) === false) { + return; + } + + $start = $tokens[$end]['parenthesis_opener']; + }//end if + } else if ($tokens[$stackPtr]['code'] === T_FOR) { + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false) { + return; + } + + $openingBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closingBracket = $tokens[$stackPtr]['parenthesis_closer']; + + $start = $phpcsFile->findNext(T_SEMICOLON, $openingBracket, $closingBracket); + $end = $phpcsFile->findNext(T_SEMICOLON, ($start + 1), $closingBracket); + if ($start === false || $end === false) { + return; + } + } else { + if (isset($tokens[$stackPtr]['parenthesis_opener']) === false) { + return; + } + + $start = $tokens[$stackPtr]['parenthesis_opener']; + $end = $tokens[$stackPtr]['parenthesis_closer']; + }//end if + + $requiredOps = 0; + $foundOps = 0; + $foundBooleans = 0; + + $lastNonEmpty = $start; + + for ($i = $start; $i <= $end; $i++) { + $type = $tokens[$i]['code']; + if (isset(self::$invalidOps[$tokenizer][$type]) === true) { + $error = 'Operator %s prohibited; use %s instead'; + $data = [ + $tokens[$i]['content'], + self::$invalidOps[$tokenizer][$type], + ]; + $phpcsFile->addError($error, $i, 'NotAllowed', $data); + $foundOps++; + } else if (isset(self::$validOps[$type]) === true) { + $foundOps++; + } + + if ($type === T_OPEN_PARENTHESIS + && isset($tokens[$i]['parenthesis_closer']) === true + && isset(Tokens::$functionNameTokens[$tokens[$lastNonEmpty]['code']]) === true + ) { + $i = $tokens[$i]['parenthesis_closer']; + $lastNonEmpty = $i; + continue; + } + + if ($tokens[$i]['code'] === T_TRUE || $tokens[$i]['code'] === T_FALSE) { + $foundBooleans++; + } + + if ($phpcsFile->tokenizerType !== 'JS' + && ($tokens[$i]['code'] === T_BOOLEAN_AND + || $tokens[$i]['code'] === T_BOOLEAN_OR) + ) { + $requiredOps++; + + // When the instanceof operator is used with another operator + // like ===, you can get more ops than are required. + if ($foundOps > $requiredOps) { + $foundOps = $requiredOps; + } + + // If we get to here and we have not found the right number of + // comparison operators, then we must have had an implicit + // true operation i.e., if ($a) instead of the required + // if ($a === true), so let's add an error. + if ($requiredOps !== $foundOps) { + $error = 'Implicit true comparisons prohibited; use === TRUE instead'; + $phpcsFile->addError($error, $stackPtr, 'ImplicitTrue'); + $foundOps++; + } + } + + if (isset(Tokens::$emptyTokens[$type]) === false) { + $lastNonEmpty = $i; + } + }//end for + + $requiredOps++; + + if ($phpcsFile->tokenizerType !== 'JS' + && $foundOps < $requiredOps + && ($requiredOps !== $foundBooleans) + ) { + $error = 'Implicit true comparisons prohibited; use === TRUE instead'; + $phpcsFile->addError($error, $stackPtr, 'ImplicitTrue'); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/IncrementDecrementUsageSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/IncrementDecrementUsageSniff.php new file mode 100644 index 0000000..b0af660 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/IncrementDecrementUsageSniff.php @@ -0,0 +1,225 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class IncrementDecrementUsageSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_EQUAL, + T_PLUS_EQUAL, + T_MINUS_EQUAL, + T_INC, + T_DEC, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_INC || $tokens[$stackPtr]['code'] === T_DEC) { + $this->processIncDec($phpcsFile, $stackPtr); + } else { + $this->processAssignment($phpcsFile, $stackPtr); + } + + }//end process() + + + /** + * Checks to ensure increment and decrement operators are not confusing. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + protected function processIncDec($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Work out where the variable is so we know where to + // start looking for other operators. + if ($tokens[($stackPtr - 1)]['code'] === T_VARIABLE + || ($tokens[($stackPtr - 1)]['code'] === T_STRING + && ($tokens[($stackPtr - 2)]['code'] === T_OBJECT_OPERATOR + || $tokens[($stackPtr - 2)]['code'] === T_NULLSAFE_OBJECT_OPERATOR)) + ) { + $start = ($stackPtr + 1); + } else { + $start = ($stackPtr + 2); + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $start, null, true); + if ($next === false) { + return; + } + + if (isset(Tokens::$arithmeticTokens[$tokens[$next]['code']]) === true) { + $error = 'Increment and decrement operators cannot be used in an arithmetic operation'; + $phpcsFile->addError($error, $stackPtr, 'NotAllowed'); + return; + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($start - 3), null, true); + if ($prev === false) { + return; + } + + // Check if this is in a string concat. + if ($tokens[$next]['code'] === T_STRING_CONCAT || $tokens[$prev]['code'] === T_STRING_CONCAT) { + $error = 'Increment and decrement operators must be bracketed when used in string concatenation'; + $phpcsFile->addError($error, $stackPtr, 'NoBrackets'); + } + + }//end processIncDec() + + + /** + * Checks to ensure increment and decrement operators are used. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + protected function processAssignment($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $assignedVar = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + // Not an assignment, return. + if ($tokens[$assignedVar]['code'] !== T_VARIABLE) { + return; + } + + $statementEnd = $phpcsFile->findNext([T_SEMICOLON, T_CLOSE_PARENTHESIS, T_CLOSE_SQUARE_BRACKET, T_CLOSE_CURLY_BRACKET], $stackPtr); + + // If there is anything other than variables, numbers, spaces or operators we need to return. + $noiseTokens = $phpcsFile->findNext([T_LNUMBER, T_VARIABLE, T_WHITESPACE, T_PLUS, T_MINUS, T_OPEN_PARENTHESIS], ($stackPtr + 1), $statementEnd, true); + + if ($noiseTokens !== false) { + return; + } + + // If we are already using += or -=, we need to ignore + // the statement if a variable is being used. + if ($tokens[$stackPtr]['code'] !== T_EQUAL) { + $nextVar = $phpcsFile->findNext(T_VARIABLE, ($stackPtr + 1), $statementEnd); + if ($nextVar !== false) { + return; + } + } + + if ($tokens[$stackPtr]['code'] === T_EQUAL) { + $nextVar = ($stackPtr + 1); + $previousVariable = ($stackPtr + 1); + $variableCount = 0; + while (($nextVar = $phpcsFile->findNext(T_VARIABLE, ($nextVar + 1), $statementEnd)) !== false) { + $previousVariable = $nextVar; + $variableCount++; + } + + if ($variableCount !== 1) { + return; + } + + $nextVar = $previousVariable; + if ($tokens[$nextVar]['content'] !== $tokens[$assignedVar]['content']) { + return; + } + } + + // We have only one variable, and it's the same as what is being assigned, + // so we need to check what is being added or subtracted. + $nextNumber = ($stackPtr + 1); + $previousNumber = ($stackPtr + 1); + $numberCount = 0; + while (($nextNumber = $phpcsFile->findNext([T_LNUMBER], ($nextNumber + 1), $statementEnd, false)) !== false) { + $previousNumber = $nextNumber; + $numberCount++; + } + + if ($numberCount !== 1) { + return; + } + + $nextNumber = $previousNumber; + if ($tokens[$nextNumber]['content'] === '1') { + if ($tokens[$stackPtr]['code'] === T_EQUAL) { + $opToken = $phpcsFile->findNext([T_PLUS, T_MINUS], ($nextVar + 1), $statementEnd); + if ($opToken === false) { + // Operator was before the variable, like: + // $var = 1 + $var; + // So we ignore it. + return; + } + + $operator = $tokens[$opToken]['content']; + } else { + $operator = substr($tokens[$stackPtr]['content'], 0, 1); + } + + // If we are adding or subtracting negative value, the operator + // needs to be reversed. + if ($tokens[$stackPtr]['code'] !== T_EQUAL) { + $negative = $phpcsFile->findPrevious(T_MINUS, ($nextNumber - 1), $stackPtr); + if ($negative !== false) { + if ($operator === '+') { + $operator = '-'; + } else { + $operator = '+'; + } + } + } + + $expected = $operator.$operator.$tokens[$assignedVar]['content']; + $found = $phpcsFile->getTokensAsString($assignedVar, ($statementEnd - $assignedVar + 1)); + + if ($operator === '+') { + $error = 'Increment'; + } else { + $error = 'Decrement'; + } + + $error .= " operators should be used where possible; found \"$found\" but expected \"$expected\""; + $phpcsFile->addError($error, $stackPtr, 'Found'); + }//end if + + }//end processAssignment() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ValidLogicalOperatorsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ValidLogicalOperatorsSniff.php new file mode 100644 index 0000000..720e472 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ValidLogicalOperatorsSniff.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ValidLogicalOperatorsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_LOGICAL_AND, + T_LOGICAL_OR, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $replacements = [ + 'and' => '&&', + 'or' => '||', + ]; + + $operator = strtolower($tokens[$stackPtr]['content']); + if (isset($replacements[$operator]) === false) { + return; + } + + $error = 'Logical operator "%s" is prohibited; use "%s" instead'; + $data = [ + $operator, + $replacements[$operator], + ]; + $phpcsFile->addError($error, $stackPtr, 'NotAllowed', $data); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/CommentedOutCodeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/CommentedOutCodeSniff.php new file mode 100644 index 0000000..59e91f0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/CommentedOutCodeSniff.php @@ -0,0 +1,288 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Exceptions\TokenizerException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class CommentedOutCodeSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'CSS', + ]; + + /** + * If a comment is more than $maxPercentage% code, a warning will be shown. + * + * @var integer + */ + public $maxPercentage = 35; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_COMMENT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int|void Integer stack pointer to skip forward or void to continue + * normal file processing. + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore comments at the end of code blocks. + if (substr($tokens[$stackPtr]['content'], 0, 6) === '//end ') { + return; + } + + $content = ''; + $lastLineSeen = $tokens[$stackPtr]['line']; + $commentStyle = 'line'; + if (strpos($tokens[$stackPtr]['content'], '/*') === 0) { + $commentStyle = 'block'; + } + + $lastCommentBlockToken = $stackPtr; + for ($i = $stackPtr; $i < $phpcsFile->numTokens; $i++) { + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === false) { + break; + } + + if ($tokens[$i]['code'] === T_WHITESPACE) { + continue; + } + + if (isset(Tokens::$phpcsCommentTokens[$tokens[$i]['code']]) === true) { + $lastLineSeen = $tokens[$i]['line']; + continue; + } + + if ($commentStyle === 'line' + && ($lastLineSeen + 1) <= $tokens[$i]['line'] + && strpos($tokens[$i]['content'], '/*') === 0 + ) { + // First non-whitespace token on a new line is start of a different style comment. + break; + } + + if ($commentStyle === 'line' + && ($lastLineSeen + 1) < $tokens[$i]['line'] + ) { + // Blank line breaks a '//' style comment block. + break; + } + + /* + Trim as much off the comment as possible so we don't + have additional whitespace tokens or comment tokens + */ + + $tokenContent = trim($tokens[$i]['content']); + $break = false; + + if ($commentStyle === 'line') { + if (substr($tokenContent, 0, 2) === '//') { + $tokenContent = substr($tokenContent, 2); + } + + if (substr($tokenContent, 0, 1) === '#') { + $tokenContent = substr($tokenContent, 1); + } + } else { + if (substr($tokenContent, 0, 3) === '/**') { + $tokenContent = substr($tokenContent, 3); + } + + if (substr($tokenContent, 0, 2) === '/*') { + $tokenContent = substr($tokenContent, 2); + } + + if (substr($tokenContent, -2) === '*/') { + $tokenContent = substr($tokenContent, 0, -2); + $break = true; + } + + if (substr($tokenContent, 0, 1) === '*') { + $tokenContent = substr($tokenContent, 1); + } + }//end if + + $content .= $tokenContent.$phpcsFile->eolChar; + $lastLineSeen = $tokens[$i]['line']; + + $lastCommentBlockToken = $i; + + if ($break === true) { + // Closer of a block comment found. + break; + } + }//end for + + // Ignore typical warning suppression annotations from other tools. + if (preg_match('`^\s*@[A-Za-z()\._-]+\s*$`', $content) === 1) { + return ($lastCommentBlockToken + 1); + } + + // Quite a few comments use multiple dashes, equals signs etc + // to frame comments and licence headers. + $content = preg_replace('/[-=#*]{2,}/', '-', $content); + + // Random numbers sitting inside the content can throw parse errors + // for invalid literals in PHP7+, so strip those. + $content = preg_replace('/\d+/', '', $content); + + $content = trim($content); + + if ($content === '') { + return ($lastCommentBlockToken + 1); + } + + if ($phpcsFile->tokenizerType === 'PHP') { + $content = ''; + } + + // Because we are not really parsing code, the tokenizer can throw all sorts + // of errors that don't mean anything, so ignore them. + $oldErrors = ini_get('error_reporting'); + ini_set('error_reporting', 0); + try { + $tokenizerClass = get_class($phpcsFile->tokenizer); + $tokenizer = new $tokenizerClass($content, $phpcsFile->config, $phpcsFile->eolChar); + $stringTokens = $tokenizer->getTokens(); + } catch (TokenizerException $e) { + // We couldn't check the comment, so ignore it. + ini_set('error_reporting', $oldErrors); + return ($lastCommentBlockToken + 1); + } + + ini_set('error_reporting', $oldErrors); + + $numTokens = count($stringTokens); + + /* + We know what the first two and last two tokens should be + (because we put them there) so ignore this comment if those + tokens were not parsed correctly. It obviously means this is not + valid code. + */ + + // First token is always the opening tag. + if ($stringTokens[0]['code'] !== T_OPEN_TAG) { + return ($lastCommentBlockToken + 1); + } else { + array_shift($stringTokens); + --$numTokens; + } + + // Last token is always the closing tag, unless something went wrong. + if (isset($stringTokens[($numTokens - 1)]) === false + || $stringTokens[($numTokens - 1)]['code'] !== T_CLOSE_TAG + ) { + return ($lastCommentBlockToken + 1); + } else { + array_pop($stringTokens); + --$numTokens; + } + + // Second last token is always whitespace or a comment, depending + // on the code inside the comment. + if ($phpcsFile->tokenizerType === 'PHP') { + if (isset(Tokens::$emptyTokens[$stringTokens[($numTokens - 1)]['code']]) === false) { + return ($lastCommentBlockToken + 1); + } + + if ($stringTokens[($numTokens - 1)]['code'] === T_WHITESPACE) { + array_pop($stringTokens); + --$numTokens; + } + } + + $emptyTokens = [ + T_WHITESPACE => true, + T_STRING => true, + T_STRING_CONCAT => true, + T_ENCAPSED_AND_WHITESPACE => true, + T_NONE => true, + T_COMMENT => true, + ]; + $emptyTokens += Tokens::$phpcsCommentTokens; + + $numComment = 0; + $numPossible = 0; + $numCode = 0; + $numNonWhitespace = 0; + + for ($i = 0; $i < $numTokens; $i++) { + if (isset($emptyTokens[$stringTokens[$i]['code']]) === true) { + // Looks like comment. + $numComment++; + } else if (isset(Tokens::$comparisonTokens[$stringTokens[$i]['code']]) === true + || isset(Tokens::$arithmeticTokens[$stringTokens[$i]['code']]) === true + || $stringTokens[$i]['code'] === T_GOTO_LABEL + ) { + // Commented out HTML/XML and other docs contain a lot of these + // characters, so it is best to not use them directly. + $numPossible++; + } else { + // Looks like code. + $numCode++; + } + + if ($stringTokens[$i]['code'] !== T_WHITESPACE) { + ++$numNonWhitespace; + } + } + + // Ignore comments with only two or less non-whitespace tokens. + // Sample size too small for a reliably determination. + if ($numNonWhitespace <= 2) { + return ($lastCommentBlockToken + 1); + } + + $percentCode = ceil((($numCode / $numTokens) * 100)); + if ($percentCode > $this->maxPercentage) { + // Just in case. + $percentCode = min(100, $percentCode); + + $error = 'This comment is %s%% valid code; is this commented out code?'; + $data = [$percentCode]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } + + return ($lastCommentBlockToken + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowBooleanStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowBooleanStatementSniff.php new file mode 100644 index 0000000..24dc137 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowBooleanStatementSniff.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DisallowBooleanStatementSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$booleanOperators; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $open => $close) { + if (isset($tokens[$open]['parenthesis_owner']) === true) { + // Any owner means we are not just a simple statement. + return; + } + } + } + + $error = 'Boolean operators are not allowed outside of control structure conditions'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowComparisonAssignmentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowComparisonAssignmentSniff.php new file mode 100644 index 0000000..57dabbf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowComparisonAssignmentSniff.php @@ -0,0 +1,112 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DisallowComparisonAssignmentSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_EQUAL]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore default value assignments in function definitions. + $function = $phpcsFile->findPrevious(T_FUNCTION, ($stackPtr - 1), null, false, null, true); + if ($function !== false) { + $opener = $tokens[$function]['parenthesis_opener']; + $closer = $tokens[$function]['parenthesis_closer']; + if ($opener < $stackPtr && $closer > $stackPtr) { + return; + } + } + + // Ignore values in array definitions or match structures. + $nextNonEmpty = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($stackPtr + 1), + null, + true + ); + + if ($nextNonEmpty !== false + && ($tokens[$nextNonEmpty]['code'] === T_ARRAY + || $tokens[$nextNonEmpty]['code'] === T_MATCH) + ) { + return; + } + + // Ignore function calls. + $ignore = [ + T_NULLSAFE_OBJECT_OPERATOR, + T_OBJECT_OPERATOR, + T_STRING, + T_VARIABLE, + T_WHITESPACE, + ]; + + $next = $phpcsFile->findNext($ignore, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_CLOSURE + || ($tokens[$next]['code'] === T_OPEN_PARENTHESIS + && $tokens[($next - 1)]['code'] === T_STRING) + ) { + // Code will look like: $var = myFunction( + // and will be ignored. + return; + } + + $endStatement = $phpcsFile->findEndOfStatement($stackPtr); + for ($i = ($stackPtr + 1); $i < $endStatement; $i++) { + if ((isset(Tokens::$comparisonTokens[$tokens[$i]['code']]) === true + && $tokens[$i]['code'] !== T_COALESCE) + || $tokens[$i]['code'] === T_INLINE_THEN + ) { + $error = 'The value of a comparison must not be assigned to a variable'; + $phpcsFile->addError($error, $stackPtr, 'AssignedComparison'); + break; + } + + if (isset(Tokens::$booleanOperators[$tokens[$i]['code']]) === true + || $tokens[$i]['code'] === T_BOOLEAN_NOT + ) { + $error = 'The value of a boolean operation must not be assigned to a variable'; + $phpcsFile->addError($error, $stackPtr, 'AssignedBool'); + break; + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowInlineIfSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowInlineIfSniff.php new file mode 100644 index 0000000..f2620c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowInlineIfSniff.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowInlineIfSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_INLINE_THEN]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $phpcsFile->addError('Inline IF statements are not allowed', $stackPtr, 'Found'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowMultipleAssignmentsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowMultipleAssignmentsSniff.php new file mode 100644 index 0000000..06df652 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowMultipleAssignmentsSniff.php @@ -0,0 +1,186 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class DisallowMultipleAssignmentsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_EQUAL]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Ignore default value assignments in function definitions. + $function = $phpcsFile->findPrevious([T_FUNCTION, T_CLOSURE, T_FN], ($stackPtr - 1), null, false, null, true); + if ($function !== false) { + $opener = $tokens[$function]['parenthesis_opener']; + $closer = $tokens[$function]['parenthesis_closer']; + if ($opener < $stackPtr && $closer > $stackPtr) { + return; + } + } + + // Ignore assignments in WHILE loop conditions. + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $nested = $tokens[$stackPtr]['nested_parenthesis']; + foreach ($nested as $opener => $closer) { + if (isset($tokens[$opener]['parenthesis_owner']) === true + && $tokens[$tokens[$opener]['parenthesis_owner']]['code'] === T_WHILE + ) { + return; + } + } + } + + // Ignore member var definitions. + if (empty($tokens[$stackPtr]['conditions']) === false) { + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if (isset(Tokens::$ooScopeTokens[$tokens[$deepestScope]['code']]) === true) { + return; + } + } + + /* + The general rule is: + Find an equal sign and go backwards along the line. If you hit an + end bracket, skip to the opening bracket. When you find a variable, + stop. That variable must be the first non-empty token on the line + or in the statement. If not, throw an error. + */ + + for ($varToken = ($stackPtr - 1); $varToken >= 0; $varToken--) { + if (in_array($tokens[$varToken]['code'], [T_SEMICOLON, T_OPEN_CURLY_BRACKET], true) === true) { + // We've reached the next statement, so we + // didn't find a variable. + return; + } + + // Skip brackets. + if (isset($tokens[$varToken]['parenthesis_opener']) === true && $tokens[$varToken]['parenthesis_opener'] < $varToken) { + $varToken = $tokens[$varToken]['parenthesis_opener']; + continue; + } + + if (isset($tokens[$varToken]['bracket_opener']) === true) { + $varToken = $tokens[$varToken]['bracket_opener']; + continue; + } + + if ($tokens[$varToken]['code'] === T_VARIABLE) { + // We found our variable. + break; + } + }//end for + + if ($varToken <= 0) { + // Didn't find a variable. + return; + } + + $start = $phpcsFile->findStartOfStatement($varToken); + + $allowed = Tokens::$emptyTokens; + + $allowed[T_STRING] = T_STRING; + $allowed[T_NS_SEPARATOR] = T_NS_SEPARATOR; + $allowed[T_DOUBLE_COLON] = T_DOUBLE_COLON; + $allowed[T_OBJECT_OPERATOR] = T_OBJECT_OPERATOR; + $allowed[T_ASPERAND] = T_ASPERAND; + $allowed[T_DOLLAR] = T_DOLLAR; + $allowed[T_SELF] = T_SELF; + $allowed[T_PARENT] = T_PARENT; + $allowed[T_STATIC] = T_STATIC; + + $varToken = $phpcsFile->findPrevious($allowed, ($varToken - 1), null, true); + + if ($varToken < $start + && $tokens[$varToken]['code'] !== T_OPEN_PARENTHESIS + && $tokens[$varToken]['code'] !== T_OPEN_SQUARE_BRACKET + ) { + $varToken = $start; + } + + // Ignore the first part of FOR loops as we are allowed to + // assign variables there even though the variable is not the + // first thing on the line. + if ($tokens[$varToken]['code'] === T_OPEN_PARENTHESIS && isset($tokens[$varToken]['parenthesis_owner']) === true) { + $owner = $tokens[$varToken]['parenthesis_owner']; + if ($tokens[$owner]['code'] === T_FOR) { + return; + } + } + + if ($tokens[$varToken]['code'] === T_VARIABLE + || $tokens[$varToken]['code'] === T_OPEN_TAG + || $tokens[$varToken]['code'] === T_GOTO_LABEL + || $tokens[$varToken]['code'] === T_INLINE_THEN + || $tokens[$varToken]['code'] === T_INLINE_ELSE + || $tokens[$varToken]['code'] === T_SEMICOLON + || $tokens[$varToken]['code'] === T_CLOSE_PARENTHESIS + || isset($allowed[$tokens[$varToken]['code']]) === true + ) { + return; + } + + $error = 'Assignments must be the first block of code on a line'; + $errorCode = 'Found'; + + if (isset($nested) === true) { + $controlStructures = [ + T_IF => T_IF, + T_ELSEIF => T_ELSEIF, + T_SWITCH => T_SWITCH, + T_CASE => T_CASE, + T_FOR => T_FOR, + T_MATCH => T_MATCH, + ]; + foreach ($nested as $opener => $closer) { + if (isset($tokens[$opener]['parenthesis_owner']) === true + && isset($controlStructures[$tokens[$tokens[$opener]['parenthesis_owner']]['code']]) === true + ) { + $errorCode .= 'InControlStructure'; + break; + } + } + } + + $phpcsFile->addError($error, $stackPtr, $errorCode); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowSizeFunctionsInLoopsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowSizeFunctionsInLoopsSniff.php new file mode 100644 index 0000000..5d71c3e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowSizeFunctionsInLoopsSniff.php @@ -0,0 +1,116 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DisallowSizeFunctionsInLoopsSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * An array of functions we don't want in the condition of loops. + * + * @var array + */ + protected $forbiddenFunctions = [ + 'PHP' => [ + 'sizeof' => true, + 'strlen' => true, + 'count' => true, + ], + 'JS' => ['length' => true], + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_WHILE, + T_FOR, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $tokenizer = $phpcsFile->tokenizerType; + $openBracket = $tokens[$stackPtr]['parenthesis_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + + if ($tokens[$stackPtr]['code'] === T_FOR) { + // We only want to check the condition in FOR loops. + $start = $phpcsFile->findNext(T_SEMICOLON, ($openBracket + 1)); + $end = $phpcsFile->findPrevious(T_SEMICOLON, ($closeBracket - 1)); + } else { + $start = $openBracket; + $end = $closeBracket; + } + + for ($i = ($start + 1); $i < $end; $i++) { + if ($tokens[$i]['code'] === T_STRING + && isset($this->forbiddenFunctions[$tokenizer][$tokens[$i]['content']]) === true + ) { + $functionName = $tokens[$i]['content']; + if ($tokenizer === 'JS') { + // Needs to be in the form object.function to be valid. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($i - 1), null, true); + if ($prev === false || $tokens[$prev]['code'] !== T_OBJECT_OPERATOR) { + continue; + } + + $functionName = 'object.'.$functionName; + } else { + // Make sure it isn't a member var. + if ($tokens[($i - 1)]['code'] === T_OBJECT_OPERATOR + || $tokens[($i - 1)]['code'] === T_NULLSAFE_OBJECT_OPERATOR + ) { + continue; + } + + $functionName .= '()'; + } + + $error = 'The use of %s inside a loop condition is not allowed; assign the return value to a variable and use the variable in the loop condition instead'; + $data = [$functionName]; + $phpcsFile->addError($error, $i, 'Found', $data); + }//end if + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DiscouragedFunctionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DiscouragedFunctionsSniff.php new file mode 100644 index 0000000..56fce55 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DiscouragedFunctionsSniff.php @@ -0,0 +1,38 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff as GenericForbiddenFunctionsSniff; + +class DiscouragedFunctionsSniff extends GenericForbiddenFunctionsSniff +{ + + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. IE, the + * function should just not be used. + * + * @var array + */ + public $forbiddenFunctions = [ + 'error_log' => null, + 'print_r' => null, + 'var_dump' => null, + ]; + + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = false; + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php new file mode 100644 index 0000000..816c5a0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php @@ -0,0 +1,402 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EmbeddedPhpSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // If the close php tag is on the same line as the opening + // then we have an inline embedded PHP block. + $closeTag = $phpcsFile->findNext(T_CLOSE_TAG, $stackPtr); + if ($closeTag === false || $tokens[$stackPtr]['line'] !== $tokens[$closeTag]['line']) { + $this->validateMultilineEmbeddedPhp($phpcsFile, $stackPtr); + } else { + $this->validateInlineEmbeddedPhp($phpcsFile, $stackPtr); + } + + }//end process() + + + /** + * Validates embedded PHP that exists on multiple lines. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + private function validateMultilineEmbeddedPhp($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $prevTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)); + if ($prevTag === false) { + // This is the first open tag. + return; + } + + $firstContent = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + $closingTag = $phpcsFile->findNext(T_CLOSE_TAG, $stackPtr); + if ($closingTag !== false) { + $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($closingTag + 1), $phpcsFile->numTokens, true); + if ($nextContent === false) { + // Final closing tag. It will be handled elsewhere. + return; + } + + // We have an opening and a closing tag, that lie within other content. + if ($firstContent === $closingTag) { + $error = 'Empty embedded PHP tag found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Empty'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $stackPtr; $i <= $closingTag; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + } + }//end if + + if ($tokens[$firstContent]['line'] === $tokens[$stackPtr]['line']) { + $error = 'Opening PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentAfterOpen'); + if ($fix === true) { + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr, true); + $padding = (strlen($tokens[$first]['content']) - strlen(ltrim($tokens[$first]['content']))); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($stackPtr); + $phpcsFile->fixer->addContent($stackPtr, str_repeat(' ', $padding)); + $phpcsFile->fixer->endChangeset(); + } + } else { + // Check the indent of the first line, except if it is a scope closer. + if (isset($tokens[$firstContent]['scope_closer']) === false + || $tokens[$firstContent]['scope_closer'] !== $firstContent + ) { + // Check for a blank line at the top. + if ($tokens[$firstContent]['line'] > ($tokens[$stackPtr]['line'] + 1)) { + // Find a token on the blank line to throw the error on. + $i = $stackPtr; + do { + $i++; + } while ($tokens[$i]['line'] !== ($tokens[$stackPtr]['line'] + 1)); + + $error = 'Blank line found at start of embedded PHP content'; + $fix = $phpcsFile->addFixableError($error, $i, 'SpacingBefore'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($stackPtr + 1); $i < $firstContent; $i++) { + if ($tokens[$i]['line'] === $tokens[$firstContent]['line'] + || $tokens[$i]['line'] === $tokens[$stackPtr]['line'] + ) { + continue; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr); + if ($first === false) { + $first = $phpcsFile->findFirstOnLine(T_INLINE_HTML, $stackPtr); + $indent = (strlen($tokens[$first]['content']) - strlen(ltrim($tokens[$first]['content']))); + } else { + $indent = ($tokens[($first + 1)]['column'] - 1); + } + + $contentColumn = ($tokens[$firstContent]['column'] - 1); + if ($contentColumn !== $indent) { + $error = 'First line of embedded PHP code must be indented %s spaces; %s found'; + $data = [ + $indent, + $contentColumn, + ]; + $fix = $phpcsFile->addFixableError($error, $firstContent, 'Indent', $data); + if ($fix === true) { + $padding = str_repeat(' ', $indent); + if ($contentColumn === 0) { + $phpcsFile->fixer->addContentBefore($firstContent, $padding); + } else { + $phpcsFile->fixer->replaceToken(($firstContent - 1), $padding); + } + } + } + }//end if + }//end if + + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$lastContent]['line'] === $tokens[$stackPtr]['line'] + && trim($tokens[$lastContent]['content']) !== '' + ) { + $error = 'Opening PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentBeforeOpen'); + if ($fix === true) { + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $stackPtr); + if ($first === false) { + $first = $phpcsFile->findFirstOnLine(T_INLINE_HTML, $stackPtr); + $padding = (strlen($tokens[$first]['content']) - strlen(ltrim($tokens[$first]['content']))); + } else { + $padding = ($tokens[($first + 1)]['column'] - 1); + } + + $phpcsFile->fixer->addContentBefore($stackPtr, $phpcsFile->eolChar.str_repeat(' ', $padding)); + } + } else { + // Find the first token on the first non-empty line we find. + for ($first = ($stackPtr - 1); $first > 0; $first--) { + if ($tokens[$first]['line'] === $tokens[$stackPtr]['line']) { + continue; + } else if (trim($tokens[$first]['content']) !== '') { + $first = $phpcsFile->findFirstOnLine([], $first, true); + break; + } + } + + $expected = 0; + if ($tokens[$first]['code'] === T_INLINE_HTML + && trim($tokens[$first]['content']) !== '' + ) { + $expected = (strlen($tokens[$first]['content']) - strlen(ltrim($tokens[$first]['content']))); + } else if ($tokens[$first]['code'] === T_WHITESPACE) { + $expected = ($tokens[($first + 1)]['column'] - 1); + } + + $expected += 4; + $found = ($tokens[$stackPtr]['column'] - 1); + if ($found > $expected) { + $error = 'Opening PHP tag indent incorrect; expected no more than %s spaces but found %s'; + $data = [ + $expected, + $found, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'OpenTagIndent', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), str_repeat(' ', $expected)); + } + } + }//end if + + if ($closingTag === false) { + return; + } + + $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closingTag - 1), ($stackPtr + 1), true); + $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($closingTag + 1), null, true); + + if ($tokens[$lastContent]['line'] === $tokens[$closingTag]['line']) { + $error = 'Closing PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $closingTag, 'ContentBeforeEnd'); + if ($fix === true) { + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $closingTag, true); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContentBefore($closingTag, str_repeat(' ', ($tokens[$first]['column'] - 1))); + $phpcsFile->fixer->addNewlineBefore($closingTag); + $phpcsFile->fixer->endChangeset(); + } + } else if ($tokens[$nextContent]['line'] === $tokens[$closingTag]['line']) { + $error = 'Closing PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $closingTag, 'ContentAfterEnd'); + if ($fix === true) { + $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $closingTag, true); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($closingTag); + $phpcsFile->fixer->addContent($closingTag, str_repeat(' ', ($tokens[$first]['column'] - 1))); + $phpcsFile->fixer->endChangeset(); + } + }//end if + + $next = $phpcsFile->findNext(T_OPEN_TAG, ($closingTag + 1)); + if ($next === false) { + return; + } + + // Check for a blank line at the bottom. + if ((isset($tokens[$lastContent]['scope_closer']) === false + || $tokens[$lastContent]['scope_closer'] !== $lastContent) + && $tokens[$lastContent]['line'] < ($tokens[$closingTag]['line'] - 1) + ) { + // Find a token on the blank line to throw the error on. + $i = $closingTag; + do { + $i--; + } while ($tokens[$i]['line'] !== ($tokens[$closingTag]['line'] - 1)); + + $error = 'Blank line found at end of embedded PHP content'; + $fix = $phpcsFile->addFixableError($error, $i, 'SpacingAfter'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($lastContent + 1); $i < $closingTag; $i++) { + if ($tokens[$i]['line'] === $tokens[$lastContent]['line'] + || $tokens[$i]['line'] === $tokens[$closingTag]['line'] + ) { + continue; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + }//end if + + }//end validateMultilineEmbeddedPhp() + + + /** + * Validates embedded PHP that exists on one line. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + private function validateInlineEmbeddedPhp($phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // We only want one line PHP sections, so return if the closing tag is + // on the next line. + $closeTag = $phpcsFile->findNext(T_CLOSE_TAG, $stackPtr, null, false); + if ($tokens[$stackPtr]['line'] !== $tokens[$closeTag]['line']) { + return; + } + + // Check that there is one, and only one space at the start of the statement. + $firstContent = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $closeTag, true); + + if ($firstContent === false) { + $error = 'Empty embedded PHP tag found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Empty'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $stackPtr; $i <= $closeTag; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + + return; + } + + // The open tag token always contains a single space after it. + $leadingSpace = 1; + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $leadingSpace = ($tokens[($stackPtr + 1)]['length'] + 1); + } + + if ($leadingSpace !== 1) { + $error = 'Expected 1 space after opening PHP tag; %s found'; + $data = [$leadingSpace]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterOpen', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + } + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($closeTag - 1), $stackPtr, true); + if ($prev !== $stackPtr) { + if ((isset($tokens[$prev]['scope_opener']) === false + || $tokens[$prev]['scope_opener'] !== $prev) + && (isset($tokens[$prev]['scope_closer']) === false + || $tokens[$prev]['scope_closer'] !== $prev) + && $tokens[$prev]['code'] !== T_SEMICOLON + ) { + $error = 'Inline PHP statement must end with a semicolon'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSemicolon'); + if ($fix === true) { + $phpcsFile->fixer->addContent($prev, ';'); + } + } else if ($tokens[$prev]['code'] === T_SEMICOLON) { + $statementCount = 1; + for ($i = ($stackPtr + 1); $i < $prev; $i++) { + if ($tokens[$i]['code'] === T_SEMICOLON) { + $statementCount++; + } + } + + if ($statementCount > 1) { + $error = 'Inline PHP statement must contain a single statement; %s found'; + $data = [$statementCount]; + $phpcsFile->addError($error, $stackPtr, 'MultipleStatements', $data); + } + } + }//end if + + $trailingSpace = 0; + if ($tokens[($closeTag - 1)]['code'] === T_WHITESPACE) { + $trailingSpace = $tokens[($closeTag - 1)]['length']; + } else if (($tokens[($closeTag - 1)]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[($closeTag - 1)]['code']]) === true) + && substr($tokens[($closeTag - 1)]['content'], -1) === ' ' + ) { + $trailingSpace = (strlen($tokens[($closeTag - 1)]['content']) - strlen(rtrim($tokens[($closeTag - 1)]['content']))); + } + + if ($trailingSpace !== 1) { + $error = 'Expected 1 space before closing PHP tag; %s found'; + $data = [$trailingSpace]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBeforeClose', $data); + if ($fix === true) { + if ($trailingSpace === 0) { + $phpcsFile->fixer->addContentBefore($closeTag, ' '); + } else if ($tokens[($closeTag - 1)]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[($closeTag - 1)]['code']]) === true + ) { + $phpcsFile->fixer->replaceToken(($closeTag - 1), rtrim($tokens[($closeTag - 1)]['content']).' '); + } else { + $phpcsFile->fixer->replaceToken(($closeTag - 1), ' '); + } + } + } + + }//end validateInlineEmbeddedPhp() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EvalSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EvalSniff.php new file mode 100644 index 0000000..102bd7c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EvalSniff.php @@ -0,0 +1,48 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class EvalSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_EVAL]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $error = 'Use of eval() is discouraged'; + $phpcsFile->addWarning($error, $stackPtr, 'Discouraged'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/GlobalKeywordSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/GlobalKeywordSniff.php new file mode 100644 index 0000000..fec3ec8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/GlobalKeywordSniff.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class GlobalKeywordSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_GLOBAL]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $nextVar = $tokens[$phpcsFile->findNext([T_VARIABLE], $stackPtr)]; + $varName = str_replace('$', '', $nextVar['content']); + $error = 'Use of the "global" keyword is forbidden; use "$GLOBALS[\'%s\']" instead'; + $data = [$varName]; + $phpcsFile->addError($error, $stackPtr, 'NotAllowed', $data); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/HeredocSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/HeredocSniff.php new file mode 100644 index 0000000..a3ab8e5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/HeredocSniff.php @@ -0,0 +1,51 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class HeredocSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_START_HEREDOC, + T_START_NOWDOC, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $error = 'Use of heredoc and nowdoc syntax ("<<<") is not allowed; use standard strings or inline HTML instead'; + $phpcsFile->addError($error, $stackPtr, 'NotAllowed'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/InnerFunctionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/InnerFunctionsSniff.php new file mode 100644 index 0000000..5ec0d47 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/InnerFunctionsSniff.php @@ -0,0 +1,76 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class InnerFunctionsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['conditions']) === false) { + return; + } + + $conditions = $tokens[$stackPtr]['conditions']; + $reversedConditions = array_reverse($conditions, true); + + $outerFuncToken = null; + foreach ($reversedConditions as $condToken => $condition) { + if ($condition === T_FUNCTION || $condition === T_CLOSURE) { + $outerFuncToken = $condToken; + break; + } + + if (\array_key_exists($condition, Tokens::$ooScopeTokens) === true) { + // Ignore methods in OOP structures defined within functions. + return; + } + } + + if ($outerFuncToken === null) { + // Not a nested function. + return; + } + + $error = 'The use of inner functions is forbidden'; + $phpcsFile->addError($error, $stackPtr, 'NotAllowed'); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php new file mode 100644 index 0000000..0b671d6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php @@ -0,0 +1,167 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class LowercasePHPFunctionsSniff implements Sniff +{ + + /** + * String -> int hash map of all php built in function names + * + * @var array + */ + private $builtInFunctions; + + + /** + * Construct the LowercasePHPFunctionSniff + */ + public function __construct() + { + + $allFunctions = get_defined_functions(); + $this->builtInFunctions = array_flip($allFunctions['internal']); + + }//end __construct() + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_STRING]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $contentLc = strtolower($content); + if ($content === $contentLc) { + return; + } + + // Make sure it is an inbuilt PHP function. + // PHP_CodeSniffer can possibly include user defined functions + // through the use of vendor/autoload.php. + if (isset($this->builtInFunctions[$contentLc]) === false) { + return; + } + + // Make sure this is a function call or a use statement. + if (empty($tokens[$stackPtr]['nested_attributes']) === false) { + // Class instantiation in attribute, not function call. + return; + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($next === false) { + // Not a function call. + return; + } + + $ignore = Tokens::$emptyTokens; + $ignore[] = T_BITWISE_AND; + $prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true); + $prevPrev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true); + + if ($tokens[$next]['code'] !== T_OPEN_PARENTHESIS) { + // Is this a use statement importing a PHP native function ? + if ($tokens[$next]['code'] !== T_NS_SEPARATOR + && $tokens[$prev]['code'] === T_STRING + && $tokens[$prev]['content'] === 'function' + && $prevPrev !== false + && $tokens[$prevPrev]['code'] === T_USE + ) { + $error = 'Use statements for PHP native functions must be lowercase; expected "%s" but found "%s"'; + $data = [ + $contentLc, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'UseStatementUppercase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $contentLc); + } + } + + // No open parenthesis; not a "use function" statement nor a function call. + return; + }//end if + + if ($tokens[$prev]['code'] === T_FUNCTION) { + // Function declaration, not a function call. + return; + } + + if ($tokens[$prev]['code'] === T_NS_SEPARATOR) { + if ($prevPrev !== false + && ($tokens[$prevPrev]['code'] === T_STRING + || $tokens[$prevPrev]['code'] === T_NAMESPACE + || $tokens[$prevPrev]['code'] === T_NEW) + ) { + // Namespaced class/function, not an inbuilt function. + // Could potentially give false negatives for non-namespaced files + // when namespace\functionName() is encountered. + return; + } + } + + if ($tokens[$prev]['code'] === T_NEW) { + // Object creation, not an inbuilt function. + return; + } + + if ($tokens[$prev]['code'] === T_OBJECT_OPERATOR + || $tokens[$prev]['code'] === T_NULLSAFE_OBJECT_OPERATOR + ) { + // Not an inbuilt function. + return; + } + + if ($tokens[$prev]['code'] === T_DOUBLE_COLON) { + // Not an inbuilt function. + return; + } + + $error = 'Calls to PHP native functions must be lowercase; expected "%s" but found "%s"'; + $data = [ + $contentLc, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'CallUppercase', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $contentLc); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php new file mode 100644 index 0000000..a5db965 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php @@ -0,0 +1,303 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class NonExecutableCodeSniff implements Sniff +{ + + /** + * Tokens for terminating expressions, which can be used inline. + * + * This is in contrast to terminating statements, which cannot be used inline + * and would result in a parse error (which is not the concern of this sniff). + * + * `throw` can be used as an expression since PHP 8.0. + * {@link https://wiki.php.net/rfc/throw_expression} + * + * @var array + */ + private $expressionTokens = [ + T_EXIT => T_EXIT, + T_THROW => T_THROW, + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_BREAK, + T_CONTINUE, + T_RETURN, + T_THROW, + T_EXIT, + T_GOTO, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + + // Tokens which can be used in inline expressions need special handling. + if (isset($this->expressionTokens[$tokens[$stackPtr]['code']]) === true) { + // If this token is preceded by a logical operator, it only relates to one line + // and should be ignored. For example: fopen() or die(). + // Note: There is one exception: throw expressions can not be used with xor. + if (isset(Tokens::$booleanOperators[$tokens[$prev]['code']]) === true + && ($tokens[$stackPtr]['code'] === T_THROW && $tokens[$prev]['code'] === T_LOGICAL_XOR) === false + ) { + return; + } + + // Expressions are allowed in the `else` clause of ternaries. + if ($tokens[$prev]['code'] === T_INLINE_THEN || $tokens[$prev]['code'] === T_INLINE_ELSE) { + return; + } + + // Expressions are allowed with PHP 7.0+ null coalesce and PHP 7.4+ null coalesce equals. + if ($tokens[$prev]['code'] === T_COALESCE || $tokens[$prev]['code'] === T_COALESCE_EQUAL) { + return; + } + + // Expressions are allowed in arrow functions. + if ($tokens[$prev]['code'] === T_FN_ARROW) { + return; + } + }//end if + + // This token may be part of an inline condition. + // If we find a closing parenthesis that belongs to a condition, + // or an "else", we should ignore this token. + if ($tokens[$prev]['code'] === T_ELSE + || (isset($tokens[$prev]['parenthesis_owner']) === true + && ($tokens[$tokens[$prev]['parenthesis_owner']]['code'] === T_IF + || $tokens[$tokens[$prev]['parenthesis_owner']]['code'] === T_ELSEIF)) + ) { + return; + } + + if ($tokens[$stackPtr]['code'] === T_RETURN) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($tokens[$next]['code'] === T_SEMICOLON) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true); + if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) { + // If this is the closing brace of a function + // then this return statement doesn't return anything + // and is not required anyway. + $owner = $tokens[$next]['scope_condition']; + if ($tokens[$owner]['code'] === T_FUNCTION + || $tokens[$owner]['code'] === T_CLOSURE + ) { + $warning = 'Empty return statement not required here'; + $phpcsFile->addWarning($warning, $stackPtr, 'ReturnNotRequired'); + return; + } + } + } + } + + if (isset($tokens[$stackPtr]['scope_opener']) === true) { + $owner = $tokens[$stackPtr]['scope_condition']; + if ($tokens[$owner]['code'] === T_CASE || $tokens[$owner]['code'] === T_DEFAULT) { + // This token closes the scope of a CASE or DEFAULT statement + // so any code between this statement and the next CASE, DEFAULT or + // end of SWITCH token will not be executable. + $end = $phpcsFile->findEndOfStatement($stackPtr); + $next = $phpcsFile->findNext( + [ + T_CASE, + T_DEFAULT, + T_CLOSE_CURLY_BRACKET, + T_ENDSWITCH, + ], + ($end + 1) + ); + + if ($next !== false) { + $lastLine = $tokens[$end]['line']; + for ($i = ($stackPtr + 1); $i < $next; $i++) { + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) { + continue; + } + + $line = $tokens[$i]['line']; + if ($line > $lastLine) { + $type = substr($tokens[$stackPtr]['type'], 2); + $warning = 'Code after the %s statement on line %s cannot be executed'; + $data = [ + $type, + $tokens[$stackPtr]['line'], + ]; + $phpcsFile->addWarning($warning, $i, 'Unreachable', $data); + $lastLine = $line; + } + } + }//end if + + // That's all we have to check for these types of statements. + return; + }//end if + }//end if + + $ourConditions = array_keys($tokens[$stackPtr]['conditions']); + + if (empty($ourConditions) === false) { + $condition = array_pop($ourConditions); + + if (isset($tokens[$condition]['scope_closer']) === false) { + return; + } + + // Special case for BREAK statements sitting directly inside SWITCH + // statements. If we get to this point, we know the BREAK is not being + // used to close a CASE statement, so it is most likely non-executable + // code itself (as is the case when you put return; break; at the end of + // a case). So we need to ignore this token. + if ($tokens[$condition]['code'] === T_SWITCH + && $tokens[$stackPtr]['code'] === T_BREAK + ) { + return; + } + + $closer = $tokens[$condition]['scope_closer']; + + // If the closer for our condition is shared with other openers, + // we will need to throw errors from this token to the next + // shared opener (if there is one), not to the scope closer. + $nextOpener = null; + for ($i = ($stackPtr + 1); $i < $closer; $i++) { + if (isset($tokens[$i]['scope_closer']) === true) { + if ($tokens[$i]['scope_closer'] === $closer) { + // We found an opener that shares the same + // closing token as us. + $nextOpener = $i; + break; + } + } + }//end for + + if ($nextOpener === null) { + $end = $closer; + } else { + $end = ($nextOpener - 1); + } + } else { + // This token is in the global scope. + if ($tokens[$stackPtr]['code'] === T_BREAK) { + return; + } + + // Throw an error for all lines until the end of the file. + $end = ($phpcsFile->numTokens - 1); + }//end if + + // Find the semicolon or closing PHP tag that ends this statement, + // skipping nested statements like FOR loops and closures. + for ($start = ($stackPtr + 1); $start < $phpcsFile->numTokens; $start++) { + if ($start === $end) { + break; + } + + if (isset($tokens[$start]['parenthesis_closer']) === true + && $tokens[$start]['code'] === T_OPEN_PARENTHESIS + ) { + $start = $tokens[$start]['parenthesis_closer']; + continue; + } + + if (isset($tokens[$start]['bracket_closer']) === true + && $tokens[$start]['code'] === T_OPEN_CURLY_BRACKET + ) { + $start = $tokens[$start]['bracket_closer']; + continue; + } + + if ($tokens[$start]['code'] === T_SEMICOLON || $tokens[$start]['code'] === T_CLOSE_TAG) { + break; + } + }//end for + + if (isset($tokens[$start]) === false) { + return; + } + + $lastLine = $tokens[$start]['line']; + for ($i = ($start + 1); $i < $end; $i++) { + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true + || isset(Tokens::$bracketTokens[$tokens[$i]['code']]) === true + || $tokens[$i]['code'] === T_SEMICOLON + ) { + continue; + } + + // Skip whole functions and classes/interfaces because they are not + // technically executed code, but rather declarations that may be used. + if (isset(Tokens::$ooScopeTokens[$tokens[$i]['code']]) === true + || $tokens[$i]['code'] === T_FUNCTION + || $tokens[$i]['code'] === T_CLOSURE + ) { + if (isset($tokens[$i]['scope_closer']) === false) { + // Parse error/Live coding. + return; + } + + $i = $tokens[$i]['scope_closer']; + continue; + } + + // Skip HTML whitespace. + if ($tokens[$i]['code'] === T_INLINE_HTML && \trim($tokens[$i]['content']) === '') { + continue; + } + + // Skip PHP re-open tag (eg, after inline HTML). + if ($tokens[$i]['code'] === T_OPEN_TAG) { + continue; + } + + $line = $tokens[$i]['line']; + if ($line > $lastLine) { + $type = substr($tokens[$stackPtr]['type'], 2); + $warning = 'Code after the %s statement on line %s cannot be executed'; + $data = [ + $type, + $tokens[$stackPtr]['line'], + ]; + $phpcsFile->addWarning($warning, $i, 'Unreachable', $data); + $lastLine = $line; + } + }//end for + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MemberVarScopeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MemberVarScopeSniff.php new file mode 100644 index 0000000..3d1c83f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MemberVarScopeSniff.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; + +class MemberVarScopeSniff extends AbstractVariableSniff +{ + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $properties = $phpcsFile->getMemberProperties($stackPtr); + + if ($properties === [] || $properties['scope_specified'] !== false) { + return; + } + + $error = 'Scope modifier not specified for member variable "%s"'; + $data = [$tokens[$stackPtr]['content']]; + $phpcsFile->addError($error, $stackPtr, 'Missing', $data); + + }//end processMemberVar() + + + /** + * Processes normal variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariable() + + + /** + * Processes variables in double quoted strings. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MethodScopeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MethodScopeSniff.php new file mode 100644 index 0000000..39ed5b0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MethodScopeSniff.php @@ -0,0 +1,83 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Tokens; + +class MethodScopeSniff extends AbstractScopeSniff +{ + + + /** + * Constructs a Squiz_Sniffs_Scope_MethodScopeSniff. + */ + public function __construct() + { + parent::__construct(Tokens::$ooScopeTokens, [T_FUNCTION]); + + }//end __construct() + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * @param int $currScope The current scope opener token. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + + $properties = $phpcsFile->getMethodProperties($stackPtr); + if ($properties['scope_specified'] === false) { + $error = 'Visibility must be declared on method "%s"'; + $data = [$methodName]; + $phpcsFile->addError($error, $stackPtr, 'Missing', $data); + } + + }//end processTokenWithinScope() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php new file mode 100644 index 0000000..aab5bdb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php @@ -0,0 +1,128 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Tokens; + +class StaticThisUsageSniff extends AbstractScopeSniff +{ + + + /** + * Constructs the test with the tokens it wishes to listen for. + */ + public function __construct() + { + parent::__construct([T_CLASS, T_TRAIT, T_ENUM, T_ANON_CLASS], [T_FUNCTION]); + + }//end __construct() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * @param int $currScope A pointer to the start of the scope. + * + * @return void + */ + public function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + end($conditions); + $deepestScope = key($conditions); + if ($deepestScope !== $currScope) { + return; + } + + // Ignore abstract functions. + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + if ($next === false || $tokens[$next]['code'] !== T_STRING) { + // Not a function declaration, or incomplete. + return; + } + + $methodProps = $phpcsFile->getMethodProperties($stackPtr); + if ($methodProps['is_static'] === false) { + return; + } + + $next = $stackPtr; + $end = $tokens[$stackPtr]['scope_closer']; + + $this->checkThisUsage($phpcsFile, $next, $end); + + }//end processTokenWithinScope() + + + /** + * Check for $this variable usage between $next and $end tokens. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $next The position of the next token to check. + * @param int $end The position of the last token to check. + * + * @return void + */ + private function checkThisUsage(File $phpcsFile, $next, $end) + { + $tokens = $phpcsFile->getTokens(); + + do { + $next = $phpcsFile->findNext([T_VARIABLE, T_ANON_CLASS], ($next + 1), $end); + if ($next === false) { + continue; + } + + if ($tokens[$next]['code'] === T_ANON_CLASS) { + $this->checkThisUsage($phpcsFile, $next, $tokens[$next]['scope_opener']); + $next = $tokens[$next]['scope_closer']; + continue; + } + + if ($tokens[$next]['content'] !== '$this') { + continue; + } + + $error = 'Usage of "$this" in static methods will cause runtime errors'; + $phpcsFile->addError($error, $next, 'Found'); + } while ($next !== false); + + }//end checkThisUsage() + + + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + + }//end processTokenOutsideScope() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/ConcatenationSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/ConcatenationSpacingSniff.php new file mode 100644 index 0000000..66c3245 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/ConcatenationSpacingSniff.php @@ -0,0 +1,164 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ConcatenationSpacingSniff implements Sniff +{ + + /** + * The number of spaces before and after a string concat. + * + * @var integer + */ + public $spacing = 0; + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_STRING_CONCAT]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[($stackPtr + 2)]) === false) { + // Syntax error or live coding, bow out. + return; + } + + $ignoreBefore = false; + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($tokens[$prev]['code'] === T_END_HEREDOC || $tokens[$prev]['code'] === T_END_NOWDOC) { + // Spacing before must be preserved due to the here/nowdoc closing tag. + $ignoreBefore = true; + } + + $this->spacing = (int) $this->spacing; + + if ($ignoreBefore === false) { + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $before = 0; + } else { + if ($tokens[($stackPtr - 2)]['line'] !== $tokens[$stackPtr]['line']) { + $before = 'newline'; + } else { + $before = $tokens[($stackPtr - 1)]['length']; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing before string concat', $before); + } + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $after = 0; + } else { + if ($tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line']) { + $after = 'newline'; + } else { + $after = $tokens[($stackPtr + 1)]['length']; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing after string concat', $after); + + if (($ignoreBefore === true + || $before === $this->spacing + || ($before === 'newline' + && $this->ignoreNewlines === true)) + && ($after === $this->spacing + || ($after === 'newline' + && $this->ignoreNewlines === true)) + ) { + return; + } + + if ($this->spacing === 0) { + $message = 'Concat operator must not be surrounded by spaces'; + $data = []; + } else { + if ($this->spacing > 1) { + $message = 'Concat operator must be surrounded by %s spaces'; + } else { + $message = 'Concat operator must be surrounded by a single space'; + } + + $data = [$this->spacing]; + } + + $fix = $phpcsFile->addFixableError($message, $stackPtr, 'PaddingFound', $data); + + if ($fix === true) { + $padding = str_repeat(' ', $this->spacing); + if ($ignoreBefore === false && ($before !== 'newline' || $this->ignoreNewlines === false)) { + if ($tokens[($stackPtr - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($stackPtr - 1), $padding); + if ($this->spacing === 0 + && ($tokens[($stackPtr - 2)]['code'] === T_LNUMBER + || $tokens[($stackPtr - 2)]['code'] === T_DNUMBER) + ) { + $phpcsFile->fixer->replaceToken(($stackPtr - 2), '('.$tokens[($stackPtr - 2)]['content'].')'); + } + + $phpcsFile->fixer->endChangeset(); + } else if ($this->spacing > 0) { + $phpcsFile->fixer->addContent(($stackPtr - 1), $padding); + } + } + + if ($after !== 'newline' || $this->ignoreNewlines === false) { + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken(($stackPtr + 1), $padding); + if ($this->spacing === 0 + && ($tokens[($stackPtr + 2)]['code'] === T_LNUMBER + || $tokens[($stackPtr + 2)]['code'] === T_DNUMBER) + ) { + $phpcsFile->fixer->replaceToken(($stackPtr + 2), '('.$tokens[($stackPtr + 2)]['content'].')'); + } + + $phpcsFile->fixer->endChangeset(); + } else if ($this->spacing > 0) { + $phpcsFile->fixer->addContent($stackPtr, $padding); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php new file mode 100644 index 0000000..fb3b626 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php @@ -0,0 +1,144 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class DoubleQuoteUsageSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // If tabs are being converted to spaces by the tokeniser, the + // original content should be used instead of the converted content. + if (isset($tokens[$stackPtr]['orig_content']) === true) { + $workingString = $tokens[$stackPtr]['orig_content']; + } else { + $workingString = $tokens[$stackPtr]['content']; + } + + $lastStringToken = $stackPtr; + + $i = ($stackPtr + 1); + if (isset($tokens[$i]) === true) { + while ($i < $phpcsFile->numTokens + && $tokens[$i]['code'] === $tokens[$stackPtr]['code'] + ) { + if (isset($tokens[$i]['orig_content']) === true) { + $workingString .= $tokens[$i]['orig_content']; + } else { + $workingString .= $tokens[$i]['content']; + } + + $lastStringToken = $i; + $i++; + } + } + + $skipTo = ($lastStringToken + 1); + + // Check if it's a double quoted string. + if ($workingString[0] !== '"' || substr($workingString, -1) !== '"') { + return $skipTo; + } + + // The use of variables in double quoted strings is not allowed. + if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING) { + $stringTokens = token_get_all('addError($error, $stackPtr, 'ContainsVar', $data); + } + } + + return $skipTo; + }//end if + + $allowedChars = [ + '\0', + '\1', + '\2', + '\3', + '\4', + '\5', + '\6', + '\7', + '\n', + '\r', + '\f', + '\t', + '\v', + '\x', + '\b', + '\e', + '\u', + '\'', + ]; + + foreach ($allowedChars as $testChar) { + if (strpos($workingString, $testChar) !== false) { + return $skipTo; + } + } + + $error = 'String %s does not require double quotes; use single quotes instead'; + $data = [str_replace(["\r", "\n"], ['\r', '\n'], $workingString)]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotRequired', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $innerContent = substr($workingString, 1, -1); + $innerContent = str_replace('\"', '"', $innerContent); + $innerContent = str_replace('\\$', '$', $innerContent); + $phpcsFile->fixer->replaceToken($stackPtr, "'$innerContent'"); + while ($lastStringToken !== $stackPtr) { + $phpcsFile->fixer->replaceToken($lastStringToken, ''); + $lastStringToken--; + } + + $phpcsFile->fixer->endChangeset(); + } + + return $skipTo; + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/EchoedStringsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/EchoedStringsSniff.php new file mode 100644 index 0000000..c167d02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/EchoedStringsSniff.php @@ -0,0 +1,88 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class EchoedStringsSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_ECHO]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $firstContent = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + // If the first non-whitespace token is not an opening parenthesis, then we are not concerned. + if ($tokens[$firstContent]['code'] !== T_OPEN_PARENTHESIS) { + $phpcsFile->recordMetric($stackPtr, 'Brackets around echoed strings', 'no'); + return; + } + + $end = $phpcsFile->findNext([T_SEMICOLON, T_CLOSE_TAG], $stackPtr, null, false); + + // If the token before the semi-colon is not a closing parenthesis, then we are not concerned. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($end - 1), null, true); + if ($tokens[$prev]['code'] !== T_CLOSE_PARENTHESIS) { + $phpcsFile->recordMetric($stackPtr, 'Brackets around echoed strings', 'no'); + return; + } + + // If the parenthesis don't match, then we are not concerned. + if ($tokens[$firstContent]['parenthesis_closer'] !== $prev) { + $phpcsFile->recordMetric($stackPtr, 'Brackets around echoed strings', 'no'); + return; + } + + $phpcsFile->recordMetric($stackPtr, 'Brackets around echoed strings', 'yes'); + + if (($phpcsFile->findNext(Tokens::$operators, $stackPtr, $end, false)) === false) { + // There are no arithmetic operators in this. + $error = 'Echoed strings should not be bracketed'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'HasBracket'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($firstContent, ''); + if ($tokens[($firstContent - 1)]['code'] !== T_WHITESPACE) { + $phpcsFile->fixer->addContent(($firstContent - 1), ' '); + } + + $phpcsFile->fixer->replaceToken($prev, ''); + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/CastSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/CastSpacingSniff.php new file mode 100644 index 0000000..2ae782c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/CastSpacingSniff.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class CastSpacingSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $content = $tokens[$stackPtr]['content']; + $expected = str_replace(' ', '', $content); + $expected = str_replace("\t", '', $expected); + + if ($content !== $expected) { + $error = 'Cast statements must not contain whitespace; expected "%s" but found "%s"'; + $data = [ + $expected, + $content, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContainsWhiteSpace', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, $expected); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php new file mode 100644 index 0000000..eb6e5b2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php @@ -0,0 +1,359 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ControlStructureSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_IF, + T_WHILE, + T_FOREACH, + T_FOR, + T_SWITCH, + T_DO, + T_ELSE, + T_ELSEIF, + T_TRY, + T_CATCH, + T_FINALLY, + T_MATCH, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['parenthesis_opener']) === true + && isset($tokens[$stackPtr]['parenthesis_closer']) === true + ) { + $parenOpener = $tokens[$stackPtr]['parenthesis_opener']; + $parenCloser = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[($parenOpener + 1)]['code'] === T_WHITESPACE) { + $gap = $tokens[($parenOpener + 1)]['length']; + + if ($gap === 0) { + $phpcsFile->recordMetric($stackPtr, 'Spaces after control structure open parenthesis', 'newline'); + $gap = 'newline'; + } else { + $phpcsFile->recordMetric($stackPtr, 'Spaces after control structure open parenthesis', $gap); + } + + $error = 'Expected 0 spaces after opening bracket; %s found'; + $data = [$gap]; + $fix = $phpcsFile->addFixableError($error, ($parenOpener + 1), 'SpacingAfterOpenBrace', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($parenOpener + 1), ''); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Spaces after control structure open parenthesis', 0); + } + + if ($tokens[$parenOpener]['line'] === $tokens[$parenCloser]['line'] + && $tokens[($parenCloser - 1)]['code'] === T_WHITESPACE + ) { + $gap = $tokens[($parenCloser - 1)]['length']; + $error = 'Expected 0 spaces before closing bracket; %s found'; + $data = [$gap]; + $fix = $phpcsFile->addFixableError($error, ($parenCloser - 1), 'SpaceBeforeCloseBrace', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($parenCloser - 1), ''); + } + + if ($gap === 0) { + $phpcsFile->recordMetric($stackPtr, 'Spaces before control structure close parenthesis', 'newline'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Spaces before control structure close parenthesis', $gap); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Spaces before control structure close parenthesis', 0); + } + }//end if + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + $scopeOpener = $tokens[$stackPtr]['scope_opener']; + $scopeCloser = $tokens[$stackPtr]['scope_closer']; + + for ($firstContent = ($scopeOpener + 1); $firstContent < $phpcsFile->numTokens; $firstContent++) { + $code = $tokens[$firstContent]['code']; + + if ($code === T_WHITESPACE + || ($code === T_INLINE_HTML + && trim($tokens[$firstContent]['content']) === '') + ) { + continue; + } + + // Skip all empty tokens on the same line as the opener. + if ($tokens[$firstContent]['line'] === $tokens[$scopeOpener]['line'] + && (isset(Tokens::$emptyTokens[$code]) === true + || $code === T_CLOSE_TAG) + ) { + continue; + } + + break; + } + + // We ignore spacing for some structures that tend to have their own rules. + $ignore = [ + T_FUNCTION => true, + T_CLASS => true, + T_INTERFACE => true, + T_TRAIT => true, + T_ENUM => true, + T_DOC_COMMENT_OPEN_TAG => true, + ]; + + if (isset($ignore[$tokens[$firstContent]['code']]) === false + && $tokens[$firstContent]['line'] >= ($tokens[$scopeOpener]['line'] + 2) + ) { + $gap = ($tokens[$firstContent]['line'] - $tokens[$scopeOpener]['line'] - 1); + $phpcsFile->recordMetric($stackPtr, 'Blank lines at start of control structure', $gap); + + $error = 'Blank line found at start of control structure'; + $fix = $phpcsFile->addFixableError($error, $scopeOpener, 'SpacingAfterOpen'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $i = ($scopeOpener + 1); + while ($tokens[$i]['line'] !== $tokens[$firstContent]['line']) { + // Start removing content from the line after the opener. + if ($tokens[$i]['line'] !== $tokens[$scopeOpener]['line']) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $i++; + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Blank lines at start of control structure', 0); + }//end if + + if ($firstContent !== $scopeCloser) { + $lastContent = $phpcsFile->findPrevious( + T_WHITESPACE, + ($scopeCloser - 1), + null, + true + ); + + $lastNonEmptyContent = $phpcsFile->findPrevious( + Tokens::$emptyTokens, + ($scopeCloser - 1), + null, + true + ); + + $checkToken = $lastContent; + if (isset($tokens[$lastNonEmptyContent]['scope_condition']) === true) { + $checkToken = $tokens[$lastNonEmptyContent]['scope_condition']; + } + + if (isset($ignore[$tokens[$checkToken]['code']]) === false + && $tokens[$lastContent]['line'] <= ($tokens[$scopeCloser]['line'] - 2) + ) { + $errorToken = $scopeCloser; + for ($i = ($scopeCloser - 1); $i > $lastContent; $i--) { + if ($tokens[$i]['line'] < $tokens[$scopeCloser]['line']) { + $errorToken = $i; + break; + } + } + + $gap = ($tokens[$scopeCloser]['line'] - $tokens[$lastContent]['line'] - 1); + $phpcsFile->recordMetric($stackPtr, 'Blank lines at end of control structure', $gap); + + $error = 'Blank line found at end of control structure'; + $fix = $phpcsFile->addFixableError($error, $errorToken, 'SpacingBeforeClose'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($scopeCloser - 1); $i > $lastContent; $i--) { + if ($tokens[$i]['line'] === $tokens[$scopeCloser]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$lastContent]['line']) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Blank lines at end of control structure', 0); + }//end if + }//end if + + if ($tokens[$stackPtr]['code'] === T_MATCH) { + // Move the scope closer to the semicolon/comma. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($scopeCloser + 1), null, true); + if ($next !== false + && ($tokens[$next]['code'] === T_SEMICOLON || $tokens[$next]['code'] === T_COMMA) + ) { + $scopeCloser = $next; + } + } + + $trailingContent = $phpcsFile->findNext( + T_WHITESPACE, + ($scopeCloser + 1), + null, + true + ); + + if ($tokens[$trailingContent]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$trailingContent]['code']]) === true + ) { + // Special exception for code where the comment about + // an ELSE or ELSEIF is written between the control structures. + $nextCode = $phpcsFile->findNext( + Tokens::$emptyTokens, + ($scopeCloser + 1), + null, + true + ); + + if ($tokens[$nextCode]['code'] === T_ELSE + || $tokens[$nextCode]['code'] === T_ELSEIF + || $tokens[$trailingContent]['line'] === $tokens[$scopeCloser]['line'] + ) { + $trailingContent = $nextCode; + } + }//end if + + if ($tokens[$trailingContent]['code'] === T_ELSE) { + if ($tokens[$stackPtr]['code'] === T_IF) { + // IF with ELSE. + return; + } + } + + if ($tokens[$trailingContent]['code'] === T_WHILE + && $tokens[$stackPtr]['code'] === T_DO + ) { + // DO with WHILE. + return; + } + + if ($tokens[$trailingContent]['code'] === T_CLOSE_TAG) { + // At the end of the script or embedded code. + return; + } + + if (isset($tokens[$trailingContent]['scope_condition']) === true + && $tokens[$trailingContent]['scope_condition'] !== $trailingContent + && isset($tokens[$trailingContent]['scope_opener']) === true + && $tokens[$trailingContent]['scope_opener'] !== $trailingContent + ) { + // Another control structure's closing brace. + $owner = $tokens[$trailingContent]['scope_condition']; + if ($tokens[$owner]['code'] === T_FUNCTION) { + // The next content is the closing brace of a function + // so normal function rules apply and we can ignore it. + return; + } + + if ($tokens[$owner]['code'] === T_CLOSURE + && ($phpcsFile->hasCondition($stackPtr, [T_FUNCTION, T_CLOSURE]) === true + || isset($tokens[$stackPtr]['nested_parenthesis']) === true) + ) { + return; + } + + if ($tokens[$trailingContent]['line'] !== ($tokens[$scopeCloser]['line'] + 1)) { + $error = 'Blank line found after control structure'; + $fix = $phpcsFile->addFixableError($error, $scopeCloser, 'LineAfterClose'); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $i = ($scopeCloser + 1); + while ($tokens[$i]['line'] !== $tokens[$trailingContent]['line']) { + $phpcsFile->fixer->replaceToken($i, ''); + $i++; + } + + $phpcsFile->fixer->addNewline($scopeCloser); + $phpcsFile->fixer->endChangeset(); + } + } + } else if ($tokens[$trailingContent]['code'] !== T_ELSE + && $tokens[$trailingContent]['code'] !== T_ELSEIF + && $tokens[$trailingContent]['code'] !== T_CATCH + && $tokens[$trailingContent]['code'] !== T_FINALLY + && $tokens[$trailingContent]['line'] === ($tokens[$scopeCloser]['line'] + 1) + ) { + $error = 'No blank line found after control structure'; + $fix = $phpcsFile->addFixableError($error, $scopeCloser, 'NoLineAfterClose'); + if ($fix === true) { + $trailingContent = $phpcsFile->findNext( + T_WHITESPACE, + ($scopeCloser + 1), + null, + true + ); + + if (($tokens[$trailingContent]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$trailingContent]['code']]) === true) + && $tokens[$trailingContent]['line'] === $tokens[$scopeCloser]['line'] + ) { + $phpcsFile->fixer->addNewline($trailingContent); + } else { + $phpcsFile->fixer->addNewline($scopeCloser); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionClosingBraceSpaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionClosingBraceSpaceSniff.php new file mode 100644 index 0000000..54b9ca9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionClosingBraceSpaceSniff.php @@ -0,0 +1,164 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FunctionClosingBraceSpaceSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + // Probably an interface method. + return; + } + + $closeBrace = $tokens[$stackPtr]['scope_closer']; + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBrace - 1), null, true); + + // Special case for empty JS functions. + if ($phpcsFile->tokenizerType === 'JS' && $prevContent === $tokens[$stackPtr]['scope_opener']) { + // In this case, the opening and closing brace must be + // right next to each other. + if ($tokens[$stackPtr]['scope_closer'] !== ($tokens[$stackPtr]['scope_opener'] + 1)) { + $error = 'The opening and closing braces of empty functions must be directly next to each other; e.g., function () {}'; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBetween'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($tokens[$stackPtr]['scope_opener'] + 1); $i < $closeBrace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } + + return; + } + + $nestedFunction = false; + if ($phpcsFile->hasCondition($stackPtr, [T_FUNCTION, T_CLOSURE]) === true + || isset($tokens[$stackPtr]['nested_parenthesis']) === true + ) { + $nestedFunction = true; + } + + $braceLine = $tokens[$closeBrace]['line']; + $prevLine = $tokens[$prevContent]['line']; + $found = ($braceLine - $prevLine - 1); + + if ($nestedFunction === true) { + if ($found < 0) { + $error = 'Closing brace of nested function must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'ContentBeforeClose'); + if ($fix === true) { + $phpcsFile->fixer->addNewlineBefore($closeBrace); + } + } else if ($found > 0) { + $error = 'Expected 0 blank lines before closing brace of nested function; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBeforeNestedClose', $data); + + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $changeMade = false; + for ($i = ($prevContent + 1); $i < $closeBrace; $i++) { + // Try and maintain indentation. + if ($tokens[$i]['line'] === ($braceLine - 1)) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + $changeMade = true; + } + + // Special case for when the last content contains the newline + // token as well, like with a comment. + if ($changeMade === false) { + $phpcsFile->fixer->replaceToken(($prevContent + 1), ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + } else { + if ($found !== 1) { + if ($found < 0) { + $found = 0; + } + + $error = 'Expected 1 blank line before closing function brace; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBeforeClose', $data); + + if ($fix === true) { + if ($found > 1) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prevContent + 1); $i < ($closeBrace - 1); $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken($i, $phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } else { + // Try and maintain indentation. + if ($tokens[($closeBrace - 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->addNewlineBefore($closeBrace - 1); + } else { + $phpcsFile->fixer->addNewlineBefore($closeBrace); + } + } + } + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionOpeningBraceSpaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionOpeningBraceSpaceSniff.php new file mode 100644 index 0000000..3eff4e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionOpeningBraceSpaceSniff.php @@ -0,0 +1,98 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class FunctionOpeningBraceSpaceSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_FUNCTION, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[$stackPtr]['scope_opener']) === false) { + // Probably an interface or abstract method. + return; + } + + $openBrace = $tokens[$stackPtr]['scope_opener']; + $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($openBrace + 1), null, true); + + if ($nextContent === $tokens[$stackPtr]['scope_closer']) { + // The next bit of content is the closing brace, so this + // is an empty function and should have a blank line + // between the opening and closing braces. + return; + } + + $braceLine = $tokens[$openBrace]['line']; + $nextLine = $tokens[$nextContent]['line']; + + $found = ($nextLine - $braceLine - 1); + if ($found > 0) { + $error = 'Expected 0 blank lines after opening function brace; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $openBrace, 'SpacingAfter', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($openBrace + 1); $i < $nextContent; $i++) { + if ($tokens[$i]['line'] === $nextLine) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->addNewline($openBrace); + $phpcsFile->fixer->endChangeset(); + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php new file mode 100644 index 0000000..01cbd64 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php @@ -0,0 +1,366 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class FunctionSpacingSniff implements Sniff +{ + + /** + * The number of blank lines between functions. + * + * @var integer + */ + public $spacing = 2; + + /** + * The number of blank lines before the first function in a class. + * + * @var integer + */ + public $spacingBeforeFirst = 2; + + /** + * The number of blank lines after the last function in a class. + * + * @var integer + */ + public $spacingAfterLast = 2; + + /** + * Original properties as set in a custom ruleset (if any). + * + * @var array|null + */ + private $rulesetProperties = null; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_FUNCTION]; + + }//end register() + + + /** + * Processes this sniff when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $previousNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if ($previousNonEmpty !== false + && $tokens[$previousNonEmpty]['code'] === T_OPEN_TAG + && $tokens[$previousNonEmpty]['line'] !== 1 + ) { + // Ignore functions at the start of an embedded PHP block. + return; + } + + // If the ruleset has only overridden the spacing property, use + // that value for all spacing rules. + if ($this->rulesetProperties === null) { + $this->rulesetProperties = []; + if (isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']) === true + && isset($phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties']) === true + ) { + $this->rulesetProperties = $phpcsFile->ruleset->ruleset['Squiz.WhiteSpace.FunctionSpacing']['properties']; + if (isset($this->rulesetProperties['spacing']) === true) { + if (isset($this->rulesetProperties['spacingBeforeFirst']) === false) { + $this->spacingBeforeFirst = $this->spacing; + } + + if (isset($this->rulesetProperties['spacingAfterLast']) === false) { + $this->spacingAfterLast = $this->spacing; + } + } + } + } + + $this->spacing = (int) $this->spacing; + $this->spacingBeforeFirst = (int) $this->spacingBeforeFirst; + $this->spacingAfterLast = (int) $this->spacingAfterLast; + + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + // Must be an interface method, so the closer is the semicolon. + $closer = $phpcsFile->findNext(T_SEMICOLON, $stackPtr); + } else { + $closer = $tokens[$stackPtr]['scope_closer']; + } + + $isFirst = false; + $isLast = false; + + $ignore = ([T_WHITESPACE => T_WHITESPACE] + Tokens::$methodPrefixes); + + $prev = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true); + + while ($tokens[$prev]['code'] === T_ATTRIBUTE_END) { + // Skip past function attributes. + $prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['attribute_opener'] - 1), null, true); + } + + if ($tokens[$prev]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + // Skip past function docblocks. + $prev = $phpcsFile->findPrevious($ignore, ($tokens[$prev]['comment_opener'] - 1), null, true); + } + + if ($tokens[$prev]['code'] === T_OPEN_CURLY_BRACKET) { + $isFirst = true; + } + + $next = $phpcsFile->findNext($ignore, ($closer + 1), null, true); + if (isset(Tokens::$emptyTokens[$tokens[$next]['code']]) === true + && $tokens[$next]['line'] === $tokens[$closer]['line'] + ) { + // Skip past "end" comments. + $next = $phpcsFile->findNext($ignore, ($next + 1), null, true); + } + + if ($tokens[$next]['code'] === T_CLOSE_CURLY_BRACKET) { + $isLast = true; + } + + /* + Check the number of blank lines + after the function. + */ + + // Allow for comments on the same line as the closer. + for ($nextLineToken = ($closer + 1); $nextLineToken < $phpcsFile->numTokens; $nextLineToken++) { + if ($tokens[$nextLineToken]['line'] !== $tokens[$closer]['line']) { + break; + } + } + + $requiredSpacing = $this->spacing; + $errorCode = 'After'; + if ($isLast === true) { + $requiredSpacing = $this->spacingAfterLast; + $errorCode = 'AfterLast'; + } + + $foundLines = 0; + if ($nextLineToken === ($phpcsFile->numTokens - 1)) { + // We are at the end of the file. + // Don't check spacing after the function because this + // should be done by an EOF sniff. + $foundLines = $requiredSpacing; + } else { + $nextContent = $phpcsFile->findNext(T_WHITESPACE, $nextLineToken, null, true); + if ($nextContent === false) { + // We are at the end of the file. + // Don't check spacing after the function because this + // should be done by an EOF sniff. + $foundLines = $requiredSpacing; + } else { + $foundLines = ($tokens[$nextContent]['line'] - $tokens[$nextLineToken]['line']); + } + } + + if ($isLast === true) { + $phpcsFile->recordMetric($stackPtr, 'Function spacing after last', $foundLines); + } else { + $phpcsFile->recordMetric($stackPtr, 'Function spacing after', $foundLines); + } + + if ($foundLines !== $requiredSpacing) { + $error = 'Expected %s blank line'; + if ($requiredSpacing !== 1) { + $error .= 's'; + } + + $error .= ' after function; %s found'; + $data = [ + $requiredSpacing, + $foundLines, + ]; + + $fix = $phpcsFile->addFixableError($error, $closer, $errorCode, $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $nextLineToken; $i <= $nextContent; $i++) { + if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) { + $phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing)); + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + + /* + Check the number of blank lines + before the function. + */ + + $prevLineToken = null; + for ($i = $stackPtr; $i >= 0; $i--) { + if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { + continue; + } + + $prevLineToken = $i; + break; + } + + if ($prevLineToken === null) { + // Never found the previous line, which means + // there are 0 blank lines before the function. + $foundLines = 0; + $prevContent = 0; + $prevLineToken = 0; + } else { + $currentLine = $tokens[$stackPtr]['line']; + + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, $prevLineToken, null, true); + + if ($tokens[$prevContent]['code'] === T_COMMENT + || isset(Tokens::$phpcsCommentTokens[$tokens[$prevContent]['code']]) === true + ) { + // Ignore comments as they can have different spacing rules, and this + // isn't a proper function comment anyway. + return; + } + + while ($tokens[$prevContent]['code'] === T_ATTRIBUTE_END + && $tokens[$prevContent]['line'] === ($currentLine - 1) + ) { + // Account for function attributes. + $currentLine = $tokens[$tokens[$prevContent]['attribute_opener']]['line']; + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['attribute_opener'] - 1), null, true); + } + + if ($tokens[$prevContent]['code'] === T_DOC_COMMENT_CLOSE_TAG + && $tokens[$prevContent]['line'] === ($currentLine - 1) + ) { + // Account for function comments. + $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['comment_opener'] - 1), null, true); + } + + // Before we throw an error, check that we are not throwing an error + // for another function. We don't want to error for no blank lines after + // the previous function and no blank lines before this one as well. + $stopAt = 0; + if (isset($tokens[$prevLineToken]['conditions']) === true) { + $conditions = $tokens[$prevLineToken]['conditions']; + $conditions = array_keys($conditions); + $stopAt = array_pop($conditions); + } + + $prevLineToken = $prevContent; + $prevLine = ($tokens[$prevContent]['line'] - 1); + $i = ($stackPtr - 1); + $foundLines = 0; + + while ($currentLine !== $prevLine && $currentLine > 1 && $i > $stopAt) { + if ($tokens[$i]['code'] === T_FUNCTION) { + // Found another interface or abstract function. + return; + } + + if ($tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET + && $tokens[$tokens[$i]['scope_condition']]['code'] === T_FUNCTION + ) { + // Found a previous function. + return; + } + + $currentLine = $tokens[$i]['line']; + if ($currentLine === $prevLine) { + break; + } + + if ($tokens[($i - 1)]['line'] < $currentLine && $tokens[($i + 1)]['line'] > $currentLine) { + // This token is on a line by itself. If it is whitespace, the line is empty. + if ($tokens[$i]['code'] === T_WHITESPACE) { + $foundLines++; + } + } + + $i--; + }//end while + }//end if + + $requiredSpacing = $this->spacing; + $errorCode = 'Before'; + if ($isFirst === true) { + $requiredSpacing = $this->spacingBeforeFirst; + $errorCode = 'BeforeFirst'; + + $phpcsFile->recordMetric($stackPtr, 'Function spacing before first', $foundLines); + } else { + $phpcsFile->recordMetric($stackPtr, 'Function spacing before', $foundLines); + } + + if ($foundLines !== $requiredSpacing) { + $error = 'Expected %s blank line'; + if ($requiredSpacing !== 1) { + $error .= 's'; + } + + $error .= ' before function; %s found'; + $data = [ + $requiredSpacing, + $foundLines, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data); + if ($fix === true) { + $nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($prevContent + 1), $stackPtr); + if ($nextSpace === false) { + $nextSpace = ($stackPtr - 1); + } + + if ($foundLines < $requiredSpacing) { + $padding = str_repeat($phpcsFile->eolChar, ($requiredSpacing - $foundLines)); + $phpcsFile->fixer->addContent($prevLineToken, $padding); + } else { + $nextContent = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), null, true); + $phpcsFile->fixer->beginChangeset(); + for ($i = $nextSpace; $i < $nextContent; $i++) { + if ($tokens[$i]['line'] === $tokens[$prevContent]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) { + $phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $requiredSpacing)); + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LanguageConstructSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LanguageConstructSpacingSniff.php new file mode 100644 index 0000000..b785f54 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LanguageConstructSpacingSniff.php @@ -0,0 +1,89 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util; + +class LanguageConstructSpacingSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_ECHO, + T_PRINT, + T_RETURN, + T_INCLUDE, + T_INCLUDE_ONCE, + T_REQUIRE, + T_REQUIRE_ONCE, + T_NEW, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[($stackPtr + 1)]) === false) { + // Skip if there is no next token. + return; + } + + if ($tokens[($stackPtr + 1)]['code'] === T_SEMICOLON) { + // No content for this language construct. + return; + } + + if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { + $content = $tokens[($stackPtr + 1)]['content']; + if ($content !== ' ') { + $error = 'Language constructs must be followed by a single space; expected 1 space but found "%s"'; + $data = [Util\Common::prepareForOutput($content)]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'IncorrectSingle', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } else if ($tokens[($stackPtr + 1)]['code'] !== T_OPEN_PARENTHESIS) { + $error = 'Language constructs must be followed by a single space; expected "%s" but found "%s"'; + $data = [ + $tokens[$stackPtr]['content'].' '.$tokens[($stackPtr + 1)]['content'], + $tokens[$stackPtr]['content'].$tokens[($stackPtr + 1)]['content'], + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Incorrect', $data); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LogicalOperatorSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LogicalOperatorSpacingSniff.php new file mode 100644 index 0000000..d0f4c80 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LogicalOperatorSpacingSniff.php @@ -0,0 +1,102 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class LogicalOperatorSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$booleanOperators; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Check there is one space before the operator. + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space before logical operator; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBefore'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + } else { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + if ($tokens[$stackPtr]['line'] === $tokens[$prev]['line'] + && $tokens[($stackPtr - 1)]['length'] !== 1 + ) { + $found = $tokens[($stackPtr - 1)]['length']; + $error = 'Expected 1 space before logical operator; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'TooMuchSpaceBefore', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + } + } + + // Check there is one space after the operator. + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space after logical operator; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfter'); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + } else { + $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($tokens[$stackPtr]['line'] === $tokens[$next]['line'] + && $tokens[($stackPtr + 1)]['length'] !== 1 + ) { + $found = $tokens[($stackPtr + 1)]['length']; + $error = 'Expected 1 space after logical operator; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'TooMuchSpaceAfter', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/MemberVarSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/MemberVarSpacingSniff.php new file mode 100644 index 0000000..da149ca --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/MemberVarSpacingSniff.php @@ -0,0 +1,252 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; +use PHP_CodeSniffer\Util\Tokens; + +class MemberVarSpacingSniff extends AbstractVariableSniff +{ + + /** + * The number of blank lines between member vars. + * + * @var integer + */ + public $spacing = 1; + + /** + * The number of blank lines before the first member var. + * + * @var integer + */ + public $spacingBeforeFirst = 1; + + + /** + * Processes the function tokens within the class. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $validPrefixes = Tokens::$methodPrefixes; + $validPrefixes[] = T_VAR; + + $startOfStatement = $phpcsFile->findPrevious($validPrefixes, ($stackPtr - 1), null, false, null, true); + if ($startOfStatement === false) { + return; + } + + $endOfStatement = $phpcsFile->findNext(T_SEMICOLON, ($stackPtr + 1), null, false, null, true); + + $ignore = $validPrefixes; + $ignore[T_WHITESPACE] = T_WHITESPACE; + + $start = $startOfStatement; + for ($prev = ($startOfStatement - 1); $prev >= 0; $prev--) { + if (isset($ignore[$tokens[$prev]['code']]) === true) { + continue; + } + + if ($tokens[$prev]['code'] === T_ATTRIBUTE_END + && isset($tokens[$prev]['attribute_opener']) === true + ) { + $prev = $tokens[$prev]['attribute_opener']; + $start = $prev; + continue; + } + + break; + } + + if (isset(Tokens::$commentTokens[$tokens[$prev]['code']]) === true) { + // Assume the comment belongs to the member var if it is on a line by itself. + $prevContent = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true); + if ($tokens[$prevContent]['line'] !== $tokens[$prev]['line']) { + // Check the spacing, but then skip it. + $foundLines = ($tokens[$startOfStatement]['line'] - $tokens[$prev]['line'] - 1); + if ($foundLines > 0) { + for ($i = ($prev + 1); $i < $startOfStatement; $i++) { + if ($tokens[$i]['column'] !== 1) { + continue; + } + + if ($tokens[$i]['code'] === T_WHITESPACE + && $tokens[$i]['line'] !== $tokens[($i + 1)]['line'] + ) { + $error = 'Expected 0 blank lines after member var comment; %s found'; + $data = [$foundLines]; + $fix = $phpcsFile->addFixableError($error, $prev, 'AfterComment', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + // Inline comments have the newline included in the content but + // docblocks do not. + if ($tokens[$prev]['code'] === T_COMMENT) { + $phpcsFile->fixer->replaceToken($prev, rtrim($tokens[$prev]['content'])); + } + + for ($i = ($prev + 1); $i <= $startOfStatement; $i++) { + if ($tokens[$i]['line'] === $tokens[$startOfStatement]['line']) { + break; + } + + // Remove the newline after the docblock, and any entirely + // empty lines before the member var. + if ($tokens[$i]['code'] === T_WHITESPACE + && $tokens[$i]['line'] === $tokens[$prev]['line'] + || ($tokens[$i]['column'] === 1 + && $tokens[$i]['line'] !== $tokens[($i + 1)]['line']) + ) { + $phpcsFile->fixer->replaceToken($i, ''); + } + } + + $phpcsFile->fixer->addNewline($prev); + $phpcsFile->fixer->endChangeset(); + }//end if + + break; + }//end if + }//end for + }//end if + + $start = $prev; + }//end if + }//end if + + // There needs to be n blank lines before the var, not counting comments. + if ($start === $startOfStatement) { + // No comment found. + $first = $phpcsFile->findFirstOnLine(Tokens::$emptyTokens, $start, true); + if ($first === false) { + $first = $start; + } + } else if ($tokens[$start]['code'] === T_DOC_COMMENT_CLOSE_TAG) { + $first = $tokens[$start]['comment_opener']; + } else { + $first = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($start - 1), null, true); + $first = $phpcsFile->findNext(array_merge(Tokens::$commentTokens, [T_ATTRIBUTE]), ($first + 1)); + } + + // Determine if this is the first member var. + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($first - 1), null, true); + if ($tokens[$prev]['code'] === T_CLOSE_CURLY_BRACKET + && isset($tokens[$prev]['scope_condition']) === true + && $tokens[$tokens[$prev]['scope_condition']]['code'] === T_FUNCTION + ) { + return; + } + + if ($tokens[$prev]['code'] === T_OPEN_CURLY_BRACKET + && isset(Tokens::$ooScopeTokens[$tokens[$tokens[$prev]['scope_condition']]['code']]) === true + ) { + $errorMsg = 'Expected %s blank line(s) before first member var; %s found'; + $errorCode = 'FirstIncorrect'; + $spacing = (int) $this->spacingBeforeFirst; + } else { + $errorMsg = 'Expected %s blank line(s) before member var; %s found'; + $errorCode = 'Incorrect'; + $spacing = (int) $this->spacing; + } + + $foundLines = ($tokens[$first]['line'] - $tokens[$prev]['line'] - 1); + + if ($errorCode === 'FirstIncorrect') { + $phpcsFile->recordMetric($stackPtr, 'Member var spacing before first', $foundLines); + } else { + $phpcsFile->recordMetric($stackPtr, 'Member var spacing before', $foundLines); + } + + if ($foundLines === $spacing) { + if ($endOfStatement !== false) { + return $endOfStatement; + } + + return; + } + + $data = [ + $spacing, + $foundLines, + ]; + + $fix = $phpcsFile->addFixableError($errorMsg, $startOfStatement, $errorCode, $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = ($prev + 1); $i < $first; $i++) { + if ($tokens[$i]['line'] === $tokens[$prev]['line']) { + continue; + } + + if ($tokens[$i]['line'] === $tokens[$first]['line']) { + for ($x = 1; $x <= $spacing; $x++) { + $phpcsFile->fixer->addNewlineBefore($i); + } + + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + }//end if + + if ($endOfStatement !== false) { + return $endOfStatement; + } + + }//end processMemberVar() + + + /** + * Processes normal variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariable() + + + /** + * Processes variables in double quoted strings. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + /* + We don't care about normal variables. + */ + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php new file mode 100644 index 0000000..1c27be7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php @@ -0,0 +1,167 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class ObjectOperatorSpacingSniff implements Sniff +{ + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OBJECT_OPERATOR, + T_DOUBLE_COLON, + T_NULLSAFE_OBJECT_OPERATOR, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $before = 0; + } else { + if ($tokens[($stackPtr - 2)]['line'] !== $tokens[$stackPtr]['line']) { + $before = 'newline'; + } else { + $before = $tokens[($stackPtr - 1)]['length']; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing before object operator', $before); + $this->checkSpacingBeforeOperator($phpcsFile, $stackPtr, $before); + + if (isset($tokens[($stackPtr + 1)]) === false + || isset($tokens[($stackPtr + 2)]) === false + ) { + return; + } + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $after = 0; + } else { + if ($tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line']) { + $after = 'newline'; + } else { + $after = $tokens[($stackPtr + 1)]['length']; + } + } + + $phpcsFile->recordMetric($stackPtr, 'Spacing after object operator', $after); + $this->checkSpacingAfterOperator($phpcsFile, $stackPtr, $after); + + }//end process() + + + /** + * Check the spacing before the operator. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param mixed $before The number of spaces found before the + * operator or the string 'newline'. + * + * @return boolean true if there was no error, false otherwise. + */ + protected function checkSpacingBeforeOperator(File $phpcsFile, $stackPtr, $before) + { + if ($before !== 0 + && ($before !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Space found before object operator'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before'); + if ($fix === true) { + $tokens = $phpcsFile->getTokens(); + $curPos = ($stackPtr - 1); + + $phpcsFile->fixer->beginChangeset(); + while ($tokens[$curPos]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($curPos, ''); + --$curPos; + } + + $phpcsFile->fixer->endChangeset(); + } + + return false; + } + + return true; + + }//end checkSpacingBeforeOperator() + + + /** + * Check the spacing after the operator. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param mixed $after The number of spaces found after the + * operator or the string 'newline'. + * + * @return boolean true if there was no error, false otherwise. + */ + protected function checkSpacingAfterOperator(File $phpcsFile, $stackPtr, $after) + { + if ($after !== 0 + && ($after !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Space found after object operator'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'After'); + if ($fix === true) { + $tokens = $phpcsFile->getTokens(); + $curPos = ($stackPtr + 1); + + $phpcsFile->fixer->beginChangeset(); + while ($tokens[$curPos]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($curPos, ''); + ++$curPos; + } + + $phpcsFile->fixer->endChangeset(); + } + + return false; + } + + return true; + + }//end checkSpacingAfterOperator() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php new file mode 100644 index 0000000..87dbed8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php @@ -0,0 +1,382 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class OperatorSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = false; + + /** + * Don't check spacing for assignment operators. + * + * This allows multiple assignment statements to be aligned. + * + * @var boolean + */ + public $ignoreSpacingBeforeAssignments = true; + + /** + * A list of tokens that aren't considered as operands. + * + * @var string[] + */ + private $nonOperandTokens = []; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + /* + First we setup an array of all the tokens that can come before + a T_MINUS or T_PLUS token to indicate that the token is not being + used as an operator. + */ + + // Trying to operate on a negative value; eg. ($var * -1). + $this->nonOperandTokens = Tokens::$operators; + + // Trying to compare a negative value; eg. ($var === -1). + $this->nonOperandTokens += Tokens::$comparisonTokens; + + // Trying to compare a negative value; eg. ($var || -1 === $b). + $this->nonOperandTokens += Tokens::$booleanOperators; + + // Trying to assign a negative value; eg. ($var = -1). + $this->nonOperandTokens += Tokens::$assignmentTokens; + + // Returning/printing a negative value; eg. (return -1). + $this->nonOperandTokens += [ + T_RETURN => T_RETURN, + T_ECHO => T_ECHO, + T_EXIT => T_EXIT, + T_PRINT => T_PRINT, + T_YIELD => T_YIELD, + T_FN_ARROW => T_FN_ARROW, + T_MATCH_ARROW => T_MATCH_ARROW, + ]; + + // Trying to use a negative value; eg. myFunction($var, -2). + $this->nonOperandTokens += [ + T_CASE => T_CASE, + T_COLON => T_COLON, + T_COMMA => T_COMMA, + T_INLINE_ELSE => T_INLINE_ELSE, + T_INLINE_THEN => T_INLINE_THEN, + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_OPEN_PARENTHESIS => T_OPEN_PARENTHESIS, + T_OPEN_SHORT_ARRAY => T_OPEN_SHORT_ARRAY, + T_OPEN_SQUARE_BRACKET => T_OPEN_SQUARE_BRACKET, + T_STRING_CONCAT => T_STRING_CONCAT, + ]; + + // Casting a negative value; eg. (array) -$a. + $this->nonOperandTokens += Tokens::$castTokens; + + /* + These are the tokens the sniff is looking for. + */ + + $targets = Tokens::$comparisonTokens; + $targets += Tokens::$operators; + $targets += Tokens::$assignmentTokens; + $targets[] = T_INLINE_THEN; + $targets[] = T_INLINE_ELSE; + $targets[] = T_INSTANCEOF; + + return $targets; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($this->isOperator($phpcsFile, $stackPtr) === false) { + return; + } + + if ($tokens[$stackPtr]['code'] === T_BITWISE_AND) { + // Check there is one space before the & operator. + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space before "&" operator; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBeforeAmp'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + + $phpcsFile->recordMetric($stackPtr, 'Space before operator', 0); + } else { + if ($tokens[($stackPtr - 2)]['line'] !== $tokens[$stackPtr]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($stackPtr - 1)]['length']; + } + + $phpcsFile->recordMetric($stackPtr, 'Space before operator', $found); + if ($found !== 1 + && ($found !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Expected 1 space before "&" operator; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBeforeAmp', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + } + } + }//end if + + $hasNext = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($hasNext === false) { + // Live coding/parse error at end of file. + return; + } + + // Check there is one space after the & operator. + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $error = 'Expected 1 space after "&" operator; 0 found'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfterAmp'); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + + $phpcsFile->recordMetric($stackPtr, 'Space after operator', 0); + } else { + if ($tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($stackPtr + 1)]['length']; + } + + $phpcsFile->recordMetric($stackPtr, 'Space after operator', $found); + if ($found !== 1 + && ($found !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Expected 1 space after "&" operator; %s found'; + $data = [$found]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfterAmp', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + }//end if + + return; + }//end if + + $operator = $tokens[$stackPtr]['content']; + + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE + && (($tokens[($stackPtr - 1)]['code'] === T_INLINE_THEN + && $tokens[($stackPtr)]['code'] === T_INLINE_ELSE) === false) + ) { + $error = "Expected 1 space before \"$operator\"; 0 found"; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceBefore'); + if ($fix === true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + + $phpcsFile->recordMetric($stackPtr, 'Space before operator', 0); + } else if (isset(Tokens::$assignmentTokens[$tokens[$stackPtr]['code']]) === false + || $this->ignoreSpacingBeforeAssignments === false + ) { + // Throw an error for assignments only if enabled using the sniff property + // because other standards allow multiple spaces to align assignments. + if ($tokens[($stackPtr - 2)]['line'] !== $tokens[$stackPtr]['line']) { + $found = 'newline'; + } else { + $found = $tokens[($stackPtr - 1)]['length']; + } + + $phpcsFile->recordMetric($stackPtr, 'Space before operator', $found); + if ($found !== 1 + && ($found !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Expected 1 space before "%s"; %s found'; + $data = [ + $operator, + $found, + ]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingBefore', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + if ($found === 'newline') { + $i = ($stackPtr - 2); + while ($tokens[$i]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($i, ''); + $i--; + } + } + + $phpcsFile->fixer->replaceToken(($stackPtr - 1), ' '); + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + $hasNext = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($hasNext === false) { + // Live coding/parse error at end of file. + return; + } + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + // Skip short ternary such as: "$foo = $bar ?: true;". + if (($tokens[$stackPtr]['code'] === T_INLINE_THEN + && $tokens[($stackPtr + 1)]['code'] === T_INLINE_ELSE) + ) { + return; + } + + $error = "Expected 1 space after \"$operator\"; 0 found"; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpaceAfter'); + if ($fix === true) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } + + $phpcsFile->recordMetric($stackPtr, 'Space after operator', 0); + } else { + if (isset($tokens[($stackPtr + 2)]) === true + && $tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line'] + ) { + $found = 'newline'; + } else { + $found = $tokens[($stackPtr + 1)]['length']; + } + + $phpcsFile->recordMetric($stackPtr, 'Space after operator', $found); + if ($found !== 1 + && ($found !== 'newline' || $this->ignoreNewlines === false) + ) { + $error = 'Expected 1 space after "%s"; %s found'; + $data = [ + $operator, + $found, + ]; + + $nextNonWhitespace = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + if ($nextNonWhitespace !== false + && isset(Tokens::$commentTokens[$tokens[$nextNonWhitespace]['code']]) === true + && $found === 'newline' + ) { + // Don't auto-fix when it's a comment or PHPCS annotation on a new line as + // it causes fixer conflicts and can cause the meaning of annotations to change. + $phpcsFile->addError($error, $stackPtr, 'SpacingAfter', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpacingAfter', $data); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + } + } + }//end if + }//end if + + }//end process() + + + /** + * Checks if an operator is actually a different type of token in the current context. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the operator in + * the stack. + * + * @return boolean + */ + protected function isOperator(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // Skip default values in function declarations. + // Skip declare statements. + if ($tokens[$stackPtr]['code'] === T_EQUAL + || $tokens[$stackPtr]['code'] === T_MINUS + ) { + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $parenthesis = array_keys($tokens[$stackPtr]['nested_parenthesis']); + $bracket = array_pop($parenthesis); + if (isset($tokens[$bracket]['parenthesis_owner']) === true) { + $function = $tokens[$bracket]['parenthesis_owner']; + if ($tokens[$function]['code'] === T_FUNCTION + || $tokens[$function]['code'] === T_CLOSURE + || $tokens[$function]['code'] === T_FN + || $tokens[$function]['code'] === T_DECLARE + ) { + return false; + } + } + } + } + + if ($tokens[$stackPtr]['code'] === T_EQUAL) { + // Skip for '=&' case. + if (isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)]['code'] === T_BITWISE_AND + ) { + return false; + } + } + + if ($tokens[$stackPtr]['code'] === T_BITWISE_AND) { + // If it's not a reference, then we expect one space either side of the + // bitwise operator. + if ($phpcsFile->isReference($stackPtr) === true) { + return false; + } + } + + if ($tokens[$stackPtr]['code'] === T_MINUS || $tokens[$stackPtr]['code'] === T_PLUS) { + // Check minus spacing, but make sure we aren't just assigning + // a minus value or returning one. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + if (isset($this->nonOperandTokens[$tokens[$prev]['code']]) === true) { + return false; + } + }//end if + + return true; + + }//end isOperator() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/PropertyLabelSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/PropertyLabelSpacingSniff.php new file mode 100644 index 0000000..a41f787 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/PropertyLabelSpacingSniff.php @@ -0,0 +1,79 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class PropertyLabelSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_PROPERTY, + T_LABEL, + ]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $colon = $phpcsFile->findNext(T_COLON, ($stackPtr + 1)); + + if ($colon !== ($stackPtr + 1)) { + $error = 'There must be no space before the colon in a property/label declaration'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ''); + } + } + + if ($tokens[($colon + 1)]['code'] !== T_WHITESPACE || $tokens[($colon + 1)]['content'] !== ' ') { + $error = 'There must be a single space after the colon in a property/label declaration'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'After'); + if ($fix === true) { + if ($tokens[($colon + 1)]['code'] === T_WHITESPACE) { + $phpcsFile->fixer->replaceToken(($colon + 1), ' '); + } else { + $phpcsFile->fixer->addContent($colon, ' '); + } + } + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php new file mode 100644 index 0000000..852759e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php @@ -0,0 +1,114 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ScopeClosingBraceSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$scopeOpeners; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile All the tokens found in the document. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + // If this is an inline condition (ie. there is no scope opener), then + // return, as this is not a new scope. + if (isset($tokens[$stackPtr]['scope_closer']) === false) { + return; + } + + // We need to actually find the first piece of content on this line, + // as if this is a method with tokens before it (public, static etc) + // or an if with an else before it, then we need to start the scope + // checking from there, rather than the current token. + $lineStart = $phpcsFile->findFirstOnLine([T_WHITESPACE, T_INLINE_HTML], $stackPtr, true); + while ($tokens[$lineStart]['code'] === T_CONSTANT_ENCAPSED_STRING + && $tokens[($lineStart - 1)]['code'] === T_CONSTANT_ENCAPSED_STRING + ) { + $lineStart = $phpcsFile->findFirstOnLine([T_WHITESPACE, T_INLINE_HTML], ($lineStart - 1), true); + } + + $startColumn = $tokens[$lineStart]['column']; + $scopeStart = $tokens[$stackPtr]['scope_opener']; + $scopeEnd = $tokens[$stackPtr]['scope_closer']; + + // Check that the closing brace is on it's own line. + $lastContent = $phpcsFile->findPrevious([T_INLINE_HTML, T_WHITESPACE, T_OPEN_TAG], ($scopeEnd - 1), $scopeStart, true); + for ($lineStart = $scopeEnd; $tokens[$lineStart]['column'] > 1; $lineStart--); + + if ($tokens[$lastContent]['line'] === $tokens[$scopeEnd]['line'] + || ($tokens[$lineStart]['code'] === T_INLINE_HTML + && trim($tokens[$lineStart]['content']) !== '') + ) { + $error = 'Closing brace must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $scopeEnd, 'ContentBefore'); + if ($fix === true) { + if ($tokens[$lastContent]['line'] === $tokens[$scopeEnd]['line']) { + $phpcsFile->fixer->addNewlineBefore($scopeEnd); + } else { + $phpcsFile->fixer->addNewlineBefore(($lineStart + 1)); + } + } + + return; + } + + // Check now that the closing brace is lined up correctly. + $lineStart = $phpcsFile->findFirstOnLine([T_WHITESPACE, T_INLINE_HTML], $scopeEnd, true); + $braceIndent = $tokens[$lineStart]['column']; + if ($tokens[$stackPtr]['code'] !== T_DEFAULT + && $tokens[$stackPtr]['code'] !== T_CASE + && $braceIndent !== $startColumn + ) { + $error = 'Closing brace indented incorrectly; expected %s spaces, found %s'; + $data = [ + ($startColumn - 1), + ($braceIndent - 1), + ]; + + $fix = $phpcsFile->addFixableError($error, $scopeEnd, 'Indent', $data); + if ($fix === true) { + $diff = ($startColumn - $braceIndent); + if ($diff > 0) { + $phpcsFile->fixer->addContentBefore($lineStart, str_repeat(' ', $diff)); + } else { + $phpcsFile->fixer->substrToken(($lineStart - 1), 0, $diff); + } + } + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeKeywordSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeKeywordSpacingSniff.php new file mode 100644 index 0000000..65cc13f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeKeywordSpacingSniff.php @@ -0,0 +1,172 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class ScopeKeywordSpacingSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $register = Tokens::$scopeModifiers; + $register[] = T_STATIC; + $register[] = T_READONLY; + return $register; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (isset($tokens[($stackPtr + 1)]) === false) { + return; + } + + $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true); + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); + + if ($tokens[$stackPtr]['code'] === T_STATIC) { + if (($nextToken === false || $tokens[$nextToken]['code'] === T_DOUBLE_COLON) + || $tokens[$prevToken]['code'] === T_NEW + ) { + // Late static binding, e.g., static:: OR new static() usage or live coding. + return; + } + + if ($prevToken !== false + && $tokens[$prevToken]['code'] === T_TYPE_UNION + ) { + // Not a scope keyword, but a union return type. + return; + } + + if ($prevToken !== false + && $tokens[$prevToken]['code'] === T_NULLABLE + ) { + // Not a scope keyword, but a return type. + return; + } + + if ($prevToken !== false + && $tokens[$prevToken]['code'] === T_COLON + ) { + $prevPrevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prevToken - 1), null, true); + if ($prevPrevToken !== false + && $tokens[$prevPrevToken]['code'] === T_CLOSE_PARENTHESIS + ) { + // Not a scope keyword, but a return type. + return; + } + } + }//end if + + if ($tokens[$prevToken]['code'] === T_AS) { + // Trait visibility change, e.g., "use HelloWorld { sayHello as private; }". + return; + } + + $isInFunctionDeclaration = false; + if (empty($tokens[$stackPtr]['nested_parenthesis']) === false) { + // Check if this is PHP 8.0 constructor property promotion. + // In that case, we can't have multi-property definitions. + $nestedParens = $tokens[$stackPtr]['nested_parenthesis']; + $lastCloseParens = end($nestedParens); + if (isset($tokens[$lastCloseParens]['parenthesis_owner']) === true + && $tokens[$tokens[$lastCloseParens]['parenthesis_owner']]['code'] === T_FUNCTION + ) { + $isInFunctionDeclaration = true; + } + } + + if ($nextToken !== false + && $tokens[$nextToken]['code'] === T_VARIABLE + && $isInFunctionDeclaration === false + ) { + $endOfStatement = $phpcsFile->findNext(T_SEMICOLON, ($nextToken + 1)); + if ($endOfStatement === false) { + // Live coding. + return; + } + + $multiProperty = $phpcsFile->findNext(T_VARIABLE, ($nextToken + 1), $endOfStatement); + if ($multiProperty !== false + && $tokens[$stackPtr]['line'] !== $tokens[$nextToken]['line'] + && $tokens[$nextToken]['line'] !== $tokens[$endOfStatement]['line'] + ) { + // Allow for multiple properties definitions to each be on their own line. + return; + } + } + + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + $spacing = 0; + } else if (isset($tokens[($stackPtr + 2)]) === false) { + // Parse error/live coding. Bow out. + return; + } else { + if ($tokens[($stackPtr + 2)]['line'] !== $tokens[$stackPtr]['line']) { + $spacing = 'newline'; + } else { + $spacing = $tokens[($stackPtr + 1)]['length']; + } + } + + if ($spacing !== 1) { + $error = 'Scope keyword "%s" must be followed by a single space; found %s'; + $data = [ + $tokens[$stackPtr]['content'], + $spacing, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Incorrect', $data); + if ($fix === true) { + if ($spacing === 0) { + $phpcsFile->fixer->addContent($stackPtr, ' '); + } else { + $phpcsFile->fixer->beginChangeset(); + + for ($i = ($stackPtr + 2); $i < $phpcsFile->numTokens; $i++) { + if (isset($tokens[$i]) === false || $tokens[$i]['code'] !== T_WHITESPACE) { + break; + } + + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); + $phpcsFile->fixer->endChangeset(); + } + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SemicolonSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SemicolonSpacingSniff.php new file mode 100644 index 0000000..e10c5ce --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SemicolonSpacingSniff.php @@ -0,0 +1,116 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; + +class SemicolonSpacingSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + ]; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_SEMICOLON]; + + }//end register() + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + $prevType = $tokens[($stackPtr - 1)]['code']; + if (isset(Tokens::$emptyTokens[$prevType]) === false) { + return; + } + + $nonSpace = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 2), null, true); + + // Detect whether this is a semi-colon for a condition in a `for()` control structure. + $forCondition = false; + if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { + $nestedParens = $tokens[$stackPtr]['nested_parenthesis']; + $closeParenthesis = end($nestedParens); + + if (isset($tokens[$closeParenthesis]['parenthesis_owner']) === true) { + $owner = $tokens[$closeParenthesis]['parenthesis_owner']; + + if ($tokens[$owner]['code'] === T_FOR) { + $forCondition = true; + $nonSpace = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 2), null, true); + } + } + } + + if ($tokens[$nonSpace]['code'] === T_SEMICOLON + || ($forCondition === true && $nonSpace === $tokens[$owner]['parenthesis_opener']) + || (isset($tokens[$nonSpace]['scope_opener']) === true + && $tokens[$nonSpace]['scope_opener'] === $nonSpace) + ) { + // Empty statement. + return; + } + + $expected = $tokens[$nonSpace]['content'].';'; + $found = $phpcsFile->getTokensAsString($nonSpace, ($stackPtr - $nonSpace)).';'; + $found = str_replace("\n", '\n', $found); + $found = str_replace("\r", '\r', $found); + $found = str_replace("\t", '\t', $found); + $error = 'Space found before semicolon; expected "%s" but found "%s"'; + $data = [ + $expected, + $found, + ]; + + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Incorrect', $data); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $i = ($stackPtr - 1); + while (($tokens[$i]['code'] === T_WHITESPACE) && ($i > $nonSpace)) { + $phpcsFile->fixer->replaceToken($i, ''); + $i--; + } + + $phpcsFile->fixer->addContent($nonSpace, ';'); + $phpcsFile->fixer->replaceToken($stackPtr, ''); + + $phpcsFile->fixer->endChangeset(); + } + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php new file mode 100644 index 0000000..f13baba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php @@ -0,0 +1,265 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; + +class SuperfluousWhitespaceSniff implements Sniff +{ + + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = [ + 'PHP', + 'JS', + 'CSS', + ]; + + /** + * If TRUE, whitespace rules are not checked for blank lines. + * + * Blank lines are those that contain only whitespace. + * + * @var boolean + */ + public $ignoreBlankLines = false; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [ + T_OPEN_TAG, + T_OPEN_TAG_WITH_ECHO, + T_CLOSE_TAG, + T_WHITESPACE, + T_COMMENT, + T_DOC_COMMENT_WHITESPACE, + T_CLOSURE, + ]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if ($tokens[$stackPtr]['code'] === T_OPEN_TAG) { + /* + Check for start of file whitespace. + */ + + if ($phpcsFile->tokenizerType !== 'PHP') { + // The first token is always the open tag inserted when tokenized + // and the second token is always the first piece of content in + // the file. If the second token is whitespace, there was + // whitespace at the start of the file. + if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { + return; + } + + if ($phpcsFile->fixer->enabled === true) { + $stackPtr = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); + } + } else { + // If it's the first token, then there is no space. + if ($stackPtr === 0) { + return; + } + + $beforeOpen = ''; + + for ($i = ($stackPtr - 1); $i >= 0; $i--) { + // If we find something that isn't inline html then there is something previous in the file. + if ($tokens[$i]['type'] !== 'T_INLINE_HTML') { + return; + } + + $beforeOpen .= $tokens[$i]['content']; + } + + // If we have ended up with inline html make sure it isn't just whitespace. + if (preg_match('`^[\pZ\s]+$`u', $beforeOpen) !== 1) { + return; + } + }//end if + + $fix = $phpcsFile->addFixableError('Additional whitespace found at start of file', $stackPtr, 'StartFile'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = 0; $i < $stackPtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else if ($tokens[$stackPtr]['code'] === T_CLOSE_TAG) { + /* + Check for end of file whitespace. + */ + + if ($phpcsFile->tokenizerType === 'PHP') { + if (isset($tokens[($stackPtr + 1)]) === false) { + // The close PHP token is the last in the file. + return; + } + + $afterClose = ''; + + for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { + // If we find something that isn't inline HTML then there + // is more to the file. + if ($tokens[$i]['type'] !== 'T_INLINE_HTML') { + return; + } + + $afterClose .= $tokens[$i]['content']; + } + + // If we have ended up with inline html make sure it isn't just whitespace. + if (preg_match('`^[\pZ\s]+$`u', $afterClose) !== 1) { + return; + } + } else { + // The last token is always the close tag inserted when tokenized + // and the second last token is always the last piece of content in + // the file. If the second last token is whitespace, there was + // whitespace at the end of the file. + $stackPtr--; + + // The pointer is now looking at the last content in the file and + // not the fake PHP end tag the tokenizer inserted. + if ($tokens[$stackPtr]['code'] !== T_WHITESPACE) { + return; + } + + // Allow a single newline at the end of the last line in the file. + if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE + && $tokens[$stackPtr]['content'] === $phpcsFile->eolChar + ) { + return; + } + }//end if + + $fix = $phpcsFile->addFixableError('Additional whitespace found at end of file', $stackPtr, 'EndFile'); + if ($fix === true) { + if ($phpcsFile->tokenizerType !== 'PHP') { + $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); + $stackPtr = ($prev + 1); + } + + $phpcsFile->fixer->beginChangeset(); + for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + + $phpcsFile->fixer->endChangeset(); + } + } else { + /* + Check for end of line whitespace. + */ + + // Ignore whitespace that is not at the end of a line. + if (isset($tokens[($stackPtr + 1)]['line']) === true + && $tokens[($stackPtr + 1)]['line'] === $tokens[$stackPtr]['line'] + ) { + return; + } + + // Ignore blank lines if required. + if ($this->ignoreBlankLines === true + && $tokens[$stackPtr]['code'] === T_WHITESPACE + && $tokens[($stackPtr - 1)]['line'] !== $tokens[$stackPtr]['line'] + ) { + return; + } + + $tokenContent = rtrim($tokens[$stackPtr]['content'], $phpcsFile->eolChar); + if (empty($tokenContent) === false) { + if ($tokenContent !== rtrim($tokenContent)) { + $fix = $phpcsFile->addFixableError('Whitespace found at end of line', $stackPtr, 'EndLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken($stackPtr, rtrim($tokenContent).$phpcsFile->eolChar); + } + } + } else if ($tokens[($stackPtr - 1)]['content'] !== rtrim($tokens[($stackPtr - 1)]['content']) + && $tokens[($stackPtr - 1)]['line'] === $tokens[$stackPtr]['line'] + ) { + $fix = $phpcsFile->addFixableError('Whitespace found at end of line', ($stackPtr - 1), 'EndLine'); + if ($fix === true) { + $phpcsFile->fixer->replaceToken(($stackPtr - 1), rtrim($tokens[($stackPtr - 1)]['content'])); + } + } + + /* + Check for multiple blank lines in a function. + */ + + if (($phpcsFile->hasCondition($stackPtr, [T_FUNCTION, T_CLOSURE]) === true) + && $tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line'] + && $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line'] + ) { + // Properties and functions in nested classes have their own rules for spacing. + $conditions = $tokens[$stackPtr]['conditions']; + $deepestScope = end($conditions); + if ($deepestScope === T_ANON_CLASS) { + return; + } + + // This is an empty line and the line before this one is not + // empty, so this could be the start of a multiple empty + // line block. + $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true); + $lines = ($tokens[$next]['line'] - $tokens[$stackPtr]['line']); + if ($lines > 1) { + $error = 'Functions must not contain multiple empty lines in a row; found %s empty lines'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'EmptyLines', [$lines]); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $i = $stackPtr; + while ($tokens[$i]['line'] !== $tokens[$next]['line']) { + $phpcsFile->fixer->replaceToken($i, ''); + $i++; + } + + $phpcsFile->fixer->addNewlineBefore($i); + $phpcsFile->fixer->endChangeset(); + } + } + }//end if + }//end if + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc new file mode 100644 index 0000000..8ffc868 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc @@ -0,0 +1,31 @@ + 'bar', + 'bar' => 'foo', +]; + +if ($foo) {} +[$a, $b] = $c; + +echo foo()[ 1 ]; + +echo $this->addedCustomFunctions['nonce']; +echo $this->deprecated_functions[ $function_name ]['version']; + +echo [ 1,2,3 ][0]; +echo [ 1,2,3 ][ 0 ]; +echo 'PHP'[ 0 ]; + +$array = []; +$var = $var[$var[$var]]]; // Syntax error +$var = $var[$var[$var]; // Syntax error + +$myArray[ /* key start */'key'] = $value; +$myArray[ /* key start */'key'/* key end */ ] = $value; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..41d6640 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.inc.fixed @@ -0,0 +1,31 @@ + 'bar', + 'bar' => 'foo', +]; + +if ($foo) {} +[$a, $b] = $c; + +echo foo()[1]; + +echo $this->addedCustomFunctions['nonce']; +echo $this->deprecated_functions[$function_name]['version']; + +echo [ 1,2,3 ][0]; +echo [ 1,2,3 ][0]; +echo 'PHP'[0]; + +$array = []; +$var = $var[$var[$var]]]; // Syntax error +$var = $var[$var[$var]; // Syntax error + +$myArray[/* key start */'key'] = $value; +$myArray[/* key start */'key'/* key end */] = $value; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.php new file mode 100644 index 0000000..14d13a8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayBracketSpacingUnitTest.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Arrays; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ArrayBracketSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayBracketSpacingSniff + */ +class ArrayBracketSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 3, + 7 => 3, + 17 => 2, + 20 => 2, + 23 => 2, + 24 => 2, + 30 => 1, + 31 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc new file mode 100644 index 0000000..5b539a3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc @@ -0,0 +1,537 @@ + 1, + ); +} + +class TestClass +{ + public $good = array( + 'width' => '', + 'height' => '', + ); + + private $_bad = Array( + 'width' => '', + 'height' => '' + ); + + + public function test() + { + $truck = array( + 'width' => '', + 'height' => '', + ); + + $plane = Array( + 'width' => '', + 'height' => '', + ); + + $car = array( + 'width' => '', + 'height' => '', + ); + + $bus = array( + 'width' => '', + 'height' => '' + ); + + $train = array ( + TRUE, + FALSE, + 'aaa' + ); + + $inline = array('aaa', 'bbb', 'ccc'); + $inline = array('aaa'); + $inline = Array('aaa'); + + $bigone = array( + 'name' => 'bigone', + 'children' => Array( + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => Array( + 'child' => 'aaa', + ), + ), + 'short_name' => 'big' + ); + } + +}//end class + +$value = array ( ); +$value = array( ); +$value = array('1'=>$one, '2' => $two, '3'=> $three, '4' =>$four); +$value = array('1'=>$one); + +if (in_array('1', array('1','2','3')) === TRUE) { + $value = in_array('1', array('1' , '2', '3','4')); +} + +$value = array( + '1'=> TRUE, + FALSE, + '3' => 'aaa',); + +$value = array( + '1'=> TRUE, + FALSE, + ); + +$value = array( + TRUE, + '1' => FALSE, + ); + +$value = array(1, + 2 , + 3 , + ); + +$value = array(1 => $one, + 2 => $two , + 3 => $three , + ); + +$value = array( + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2 + ) + ); + +// Space in second arg. +$args = array( + '"'.$this->id.'"', + (int) $hasSessions, + ); + +// No errors. +$paths = array( + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ); + +$x = array( + ); + +$x = array('test' + ); +$x = array('test', + ); +$x = array('name' => 'test', + ); + +$x = array( + $x, + ); + +$func = array( + $x, + 'get'.$x.'Replacement' + ); + +$array = array( + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ); + +$array = array( + 'input_one', + 'inputTwo', + 'input_3', + ); + +// Malformed +$foo = array(1 +, 2); + +$listItems[$aliasPath] = array('itemContent' => implode('
    ', $aliases)); + +$listItems[$aliasPath] = array( + 'itemContent' => implode('
    ', $aliases) + ); + +$x = array + ( + $x, + $y, + ); + +$x = array +( + $x, + $y, + ); + +$x = array( + + $x, + $y, + ); + +$test = array( + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ); + +$c = array('a' => 1,); + +function b() +{ + $a = array( + 'a' => a('a'), + + ); + +} + +$foo = Array('[',']',':',"\n","\r"); +$bar = Array('[',']',':',' ',' '); + +function foo() +{ + return array($a, $b->screen); +} + +$array = array( + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => array( + new \Zend\Validator\InArray(array('haystack' => array_keys($aSubjects))), + ), + ); + +$var = array( + 'ViewHelper', + array('Foo'), + 'Errors', + ); + +$data = array( + 'first', + 'second', + 'third', + // Add more here + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$data = array( + 'first', + 'second' + //'third', + ); + +$foo = array( + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ); + +$foo = array( + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ); + +$weightings = array( + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ); + +foreach (array( + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ) as $key => $value) { +} + +$ids = array( + '1', // Foo. + '13', // Bar. + ); + +array( + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + } +); + +array( + 'key1' => array( + '1', + '2', + ) +); + +$var = array( + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ); + +function test() : array +{ + return []; +} + +$fields = array( + 'id' => array('type' => 'INT'), + 'value' => array('type' => 'VARCHAR')); + +get_current_screen()->add_help_tab( array( + 'id' => << false); + +$x = array( + 'xxxx' => array('aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false), +); + +$foo = array + ('foo' => array + ('bar1' => 1 + ,'bar2' => 1 + ,'bar3' => 1 + ,'bar4' => 1 + ,'bar5' => 1 + ) + ); + +$foo = array( + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], array('notverified', 'unverified'), true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ); + +$foo = foo( + array( + // comment + ) +); + +$foo = array( + << lorem( + 1 + ), 2 => 2, +); + +$foo = array( + 'тип' => 'авто', + 'цвет' => 'синий', + ); + +$paths = array( + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ); + +$foo = array(<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ); + +$array = array( + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ); + +$foo = array( + $this->fn => 'value', + $foo->fn => 'value', + ); + +array($a, $b, +$c); + +array('a' => $a, 'b' => $b, +'c' => $c); + +array( + static function() { + return null; + }, + (array) array(), + (bool) array(), + (double) array(), + (int) array(), + (object) array(), + (string) array(), + (unset) array(), +); + +array( + 'foo', + 'bar' + // This is a non-fixable error. + , +); + +yield array( + static fn () : string => '', +); + +yield array( + static fn () : string => '', + ); + +$foo = array( + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ); + +// Intentional syntax error. +$a = array( + 'a' => + ); + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = array( + ...$a, + 'foo' => 'bar', + ); + +$x = array( + 'foo' => 'bar', + ...$a, + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ); + +$x = array( + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ); + +$x = array( + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ); + +$x = array( + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ); + + $x = + array( + 'a', + 'b', + ); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc.fixed new file mode 100644 index 0000000..5ebf715 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.1.inc.fixed @@ -0,0 +1,573 @@ + 1); +} + +class TestClass +{ + public $good = array( + 'width' => '', + 'height' => '', + ); + + private $_bad = array( + 'width' => '', + 'height' => '', + ); + + + public function test() + { + $truck = array( + 'width' => '', + 'height' => '', + ); + + $plane = array( + 'width' => '', + 'height' => '', + ); + + $car = array( + 'width' => '', + 'height' => '', + ); + + $bus = array( + 'width' => '', + 'height' => '', + ); + + $train = array( + TRUE, + FALSE, + 'aaa', + ); + + $inline = array( + 'aaa', + 'bbb', + 'ccc', + ); + $inline = array('aaa'); + $inline = array('aaa'); + + $bigone = array( + 'name' => 'bigone', + 'children' => array( + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => array('child' => 'aaa'), + ), + 'short_name' => 'big', + ); + } + +}//end class + +$value = array(); +$value = array(); +$value = array( + '1' => $one, + '2' => $two, + '3' => $three, + '4' => $four, + ); +$value = array('1' => $one); + +if (in_array('1', array('1', '2', '3')) === TRUE) { + $value = in_array('1', array('1', '2', '3', '4')); +} + +$value = array( + '1'=> TRUE, + FALSE, + '3' => 'aaa', + ); + +$value = array( + '1'=> TRUE, + FALSE, + ); + +$value = array( + TRUE, + '1' => FALSE, + ); + +$value = array( + 1, + 2, + 3, + ); + +$value = array( + 1 => $one, + 2 => $two, + 3 => $three, + ); + +$value = array( + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +$expected = array( + array( + '1' => 1, + '1' => 2, + ), + ); + +// Space in second arg. +$args = array( + '"'.$this->id.'"', + (int) $hasSessions, + ); + +// No errors. +$paths = array( + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ); + +$x = array(); + +$x = array('test'); +$x = array('test'); +$x = array('name' => 'test'); + +$x = array($x); + +$func = array( + $x, + 'get'.$x.'Replacement', + ); + +$array = array( + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ); + +$array = array( + 'input_one', + 'inputTwo', + 'input_3', + ); + +// Malformed +$foo = array( + 1, + 2, + ); + +$listItems[$aliasPath] = array('itemContent' => implode('
    ', $aliases)); + +$listItems[$aliasPath] = array( + 'itemContent' => implode('
    ', $aliases), + ); + +$x = array( + $x, + $y, + ); + +$x = array( + $x, + $y, + ); + +$x = array( + + $x, + $y, + ); + +$test = array( + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ); + +$c = array('a' => 1); + +function b() +{ + $a = array( + 'a' => a('a'), + + ); + +} + +$foo = array( + '[', + ']', + ':', + "\n", + "\r", + ); +$bar = array( + '[', + ']', + ':', + ' ', + ' ', + ); + +function foo() +{ + return array( + $a, + $b->screen, + ); +} + +$array = array( + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => array( + new \Zend\Validator\InArray(array('haystack' => array_keys($aSubjects))), + ), + ); + +$var = array( + 'ViewHelper', + array('Foo'), + 'Errors', + ); + +$data = array( + 'first', + 'second', + 'third', + // Add more here + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$data = array( + 'first', + 'second', + //'third', + ); + +$foo = array( + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ); + +$foo = array( + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ); + +$weightings = array( + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ); + +foreach (array( + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ) as $key => $value) { +} + +$ids = array( + '1', // Foo. + '13', // Bar. + ); + +array( + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + }, +); + +array( + 'key1' => array( + '1', + '2', + ), +); + +$var = array( + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ); + +function test() : array +{ + return []; +} + +$fields = array( + 'id' => array('type' => 'INT'), + 'value' => array('type' => 'VARCHAR'), + ); + +get_current_screen()->add_help_tab( array( + 'id' => << false); + +$x = array( + 'xxxx' => array( + 'aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false, + ), + ); + +$foo = array( + 'foo' => array( + 'bar1' => 1, + 'bar2' => 1, + 'bar3' => 1, + 'bar4' => 1, + 'bar5' => 1, + ), + ); + +$foo = array( + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], array('notverified', 'unverified'), true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ); + +$foo = foo( + array( + // comment + ) +); + +$foo = array( + << lorem( + 1 + ), + 2 => 2, +); + +$foo = array( + 'тип' => 'авто', + 'цвет' => 'синий', + ); + +$paths = array( + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ); + +$foo = array(<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ); + +$array = array( + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ); + +$foo = array( + $this->fn => 'value', + $foo->fn => 'value', + ); + +array( + $a, + $b, + $c, +); + +array( + 'a' => $a, + 'b' => $b, + 'c' => $c, +); + +array( + static function() { + return null; + }, + (array) array(), + (bool) array(), + (double) array(), + (int) array(), + (object) array(), + (string) array(), + (unset) array(), +); + +array( + 'foo', + 'bar' + // This is a non-fixable error. + , +); + +yield array( + static fn () : string => '', + ); + +yield array( + static fn () : string => '', + ); + +$foo = array( + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ); + +// Intentional syntax error. +$a = array( + 'a' => + ); + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = array( + ...$a, + 'foo' => 'bar', + ); + +$x = array( + 'foo' => 'bar', + ...$a, + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ); + +$x = array( + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ); + +$x = array( + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ); + +$x = array( + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ); + +$x = array( + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ); + + $x = + array( + 'a', + 'b', + ); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc new file mode 100644 index 0000000..7bcc5e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc @@ -0,0 +1,526 @@ + 1, + ]; +} + +class TestClass +{ + public $good = [ + 'width' => '', + 'height' => '', + ]; + + private $_bad = [ + 'width' => '', + 'height' => '' + ]; + + + public function test() + { + $truck = [ + 'width' => '', + 'height' => '', + ]; + + $plane = [ + 'width' => '', + 'height' => '', + ]; + + $car = [ + 'width' => '', + 'height' => '', + ]; + + $bus = [ + 'width' => '', + 'height' => '' + ]; + + $train = [ + TRUE, + FALSE, + 'aaa' + ]; + + $inline = ['aaa', 'bbb', 'ccc']; + $inline = ['aaa']; + $inline = ['aaa']; + + $bigone = [ + 'name' => 'bigone', + 'children' => [ + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => [ + 'child' => 'aaa', + ], + ], + 'short_name' => 'big' + ]; + } + +}//end class + +$value = [ ]; +$value = [ ]; +$value = ['1'=>$one, '2' => $two, '3'=> $three, '4' =>$four]; +$value = ['1'=>$one]; + +if (in_array('1', ['1','2','3']) === TRUE) { + $value = in_array('1', ['1' , '2', '3','4']); +} + +$value = [ + '1'=> TRUE, + FALSE, + '3' => 'aaa',]; + +$value = [ + '1'=> TRUE, + FALSE, + ]; + +$value = [ + TRUE, + '1' => FALSE, + ]; + +$value = [1, + 2 , + 3 , + ]; + +$value = [1 => $one, + 2 => $two , + 3 => $three , + ]; + +$value = [ + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2 + ] + ]; + +// Space in second arg. +$args = [ + '"'.$this->id.'"', + (int) $hasSessions, + ]; + +// No errors. +$paths = [ + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ]; + +$x = [ + ]; + +$x = ['test' + ]; +$x = ['test', + ]; +$x = ['name' => 'test', + ]; + +$x = [ + $x, + ]; + +$func = [ + $x, + 'get'.$x.'Replacement' + ]; + +$array = [ + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ]; + +$array = [ + 'input_one', + 'inputTwo', + 'input_3', + ]; + +// Malformed +$foo = [1 +, 2]; + +$listItems[$aliasPath] = ['itemContent' => implode('
    ', $aliases)]; + +$listItems[$aliasPath] = [ + 'itemContent' => implode('
    ', $aliases) + ]; + +$x = + [ + $x, + $y, + ]; + +$x = +[ + $x, + $y, + ]; + +$x = [ + + $x, + $y, + ]; + +$test = [ + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ]; + +$c = ['a' => 1,]; +$c->{$var}[ ] = 2; + +$foo = ['[',']',':',"\n","\r"]; +$bar = ['[',']',':',' ',' ']; + +function foo() +{ + return [$a, $b->screen]; +} + +$array = [ + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => [ + new \Zend\Validator\InArray(['haystack' => array_keys($aSubjects)]), + ], + ]; + +$var = [ + 'ViewHelper', + ['Foo'], + 'Errors', + ]; + +$data = [ + 'first', + 'second', + 'third', + // Add more here + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$data = [ + 'first', + 'second' + //'third', + ]; + +$foo = [ + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ]; + +$foo = [ + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ]; + +$weightings = [ + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ]; + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} + +$ids = [ + '1', // Foo. + '13', // Bar. + ]; + +[ + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + } +]; + +[ + 'key1' => [ + '1', + '2', + ] +]; + +$var = [ + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ]; + +function test() : array +{ + return []; +} + +$fields = [ + 'id' => ['type' => 'INT'], + 'value' => ['type' => 'VARCHAR']]; + +get_current_screen()->add_help_tab( [ + 'id' => << false]; + +$x = [ + 'xxxx' => ['aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false], +]; + +$foo = ['foo' => ['bar1' => 1 + ,'bar2' => 1 + ,'bar3' => 1 + ,'bar4' => 1 + ,'bar5' => 1 + ] + ]; + +$foo = [ + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], ['notverified', 'unverified'], true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ]; + + +$foo = foo( + [ + // comment + ] +); + +$foo = [ + << lorem( + 1 + ), 2 => 2, +]; + +$foo = [ + 'тип' => 'авто', + 'цвет' => 'синий', + ]; + +$paths = [ + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ]; + +$foo = [<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ]; + +$array = [ + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ]; + +$foo = [ + $this->fn => 'value', + $foo->fn => 'value', + ]; + +[$a, $b, +$c]; + +['a' => $a, 'b' => $b, +'c' => $c]; + +[ + static function() { + return null; + }, + (array) [], + (bool) [], + (double) [], + (int) [], + (object) [], + (string) [], + (unset) [], +]; + +[ + 'foo', + 'bar' + // This is a non-fixable error. + , +]; + +yield [ + static fn () : string => '', +]; + +yield [ + static fn () : string => '', + ]; + +$foo = [ + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ]; + +// Intentional syntax error. +$a = [ + 'a' => + ]; + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = [ + ...$a, + 'foo' => 'bar', + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ]; + +$x = [ + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ]; + +$x = [ + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ]; + +$x = [ + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ]; + + $x = + [ + 'a', + 'b', + ]; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc.fixed new file mode 100644 index 0000000..d156357 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.2.inc.fixed @@ -0,0 +1,560 @@ + 1]; +} + +class TestClass +{ + public $good = [ + 'width' => '', + 'height' => '', + ]; + + private $_bad = [ + 'width' => '', + 'height' => '', + ]; + + + public function test() + { + $truck = [ + 'width' => '', + 'height' => '', + ]; + + $plane = [ + 'width' => '', + 'height' => '', + ]; + + $car = [ + 'width' => '', + 'height' => '', + ]; + + $bus = [ + 'width' => '', + 'height' => '', + ]; + + $train = [ + TRUE, + FALSE, + 'aaa', + ]; + + $inline = [ + 'aaa', + 'bbb', + 'ccc', + ]; + $inline = ['aaa']; + $inline = ['aaa']; + + $bigone = [ + 'name' => 'bigone', + 'children' => [ + '1a' => 'child', + '11b' => 'child', + '111c' => 'child', + 'children' => ['child' => 'aaa'], + ], + 'short_name' => 'big', + ]; + } + +}//end class + +$value = []; +$value = []; +$value = [ + '1' => $one, + '2' => $two, + '3' => $three, + '4' => $four, + ]; +$value = ['1' => $one]; + +if (in_array('1', ['1', '2', '3']) === TRUE) { + $value = in_array('1', ['1', '2', '3', '4']); +} + +$value = [ + '1'=> TRUE, + FALSE, + '3' => 'aaa', + ]; + +$value = [ + '1'=> TRUE, + FALSE, + ]; + +$value = [ + TRUE, + '1' => FALSE, + ]; + +$value = [ + 1, + 2, + 3, + ]; + +$value = [ + 1 => $one, + 2 => $two, + 3 => $three, + ]; + +$value = [ + 'tag' => $tag, + 'space' => $this->_getIndentation($tag, $tagElement), + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +$expected = [ + [ + '1' => 1, + '1' => 2, + ], + ]; + +// Space in second arg. +$args = [ + '"'.$this->id.'"', + (int) $hasSessions, + ]; + +// No errors. +$paths = [ + Init::ROOT_DIR.'/Systems' => 'Systems', + Init::ROOT_DIR.'/Installer' => 'Systems', + ]; + +$x = []; + +$x = ['test']; +$x = ['test']; +$x = ['name' => 'test']; + +$x = [$x]; + +$func = [ + $x, + 'get'.$x.'Replacement', + ]; + +$array = [ + 'input_one' => 'one', + 'inputTwo' => 'two', + 'input_3' => 3, + ]; + +$array = [ + 'input_one', + 'inputTwo', + 'input_3', + ]; + +// Malformed +$foo = [ + 1, + 2, + ]; + +$listItems[$aliasPath] = ['itemContent' => implode('
    ', $aliases)]; + +$listItems[$aliasPath] = [ + 'itemContent' => implode('
    ', $aliases), + ]; + +$x = + [ + $x, + $y, + ]; + +$x = +[ + $x, + $y, +]; + +$x = [ + + $x, + $y, + ]; + +$test = [ + 'test' => TestFunction::blah( + $value1, + $value2 + ), + ]; + +$c = ['a' => 1]; +$c->{$var}[ ] = 2; + +$foo = [ + '[', + ']', + ':', + "\n", + "\r", + ]; +$bar = [ + '[', + ']', + ':', + ' ', + ' ', + ]; + +function foo() +{ + return [ + $a, + $b->screen, + ]; +} + +$array = [ + 'name' => 'contactSubject', + 'required' => TRUE, + 'validators' => [ + new \Zend\Validator\InArray(['haystack' => array_keys($aSubjects)]), + ], + ]; + +$var = [ + 'ViewHelper', + ['Foo'], + 'Errors', + ]; + +$data = [ + 'first', + 'second', + 'third', + // Add more here + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$data = [ + 'first', + 'second', + //'third', + ]; + +$foo = [ + $this->getViewName() . '.id' => 'value', + $this->getViewName() . '.title' => 'value', + ]; + +$foo = [ + $this->getViewName() . '.id', + $this->getViewName() . '.title', + ]; + +$weightings = [ + T_CLOSURE => 100, + + /* + Conditions. + */ + + T_WHILE => 50, + + /* + Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + + T_BOOLEAN_AND => 5, + + /* + Equality. + */ + + T_IS_GREATER_OR_EQUAL => 5, + ]; + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} + +$ids = [ + '1', // Foo. + '13', // Bar. + ]; + +[ + 'key1' => function($bar) { + return $bar; + }, + 'key2' => function($foo) { + return $foo; + }, + 'key3' => function($bar) { + return $bar; + }, +]; + +[ + 'key1' => [ + '1', + '2', + ], +]; + +$var = [ + 'tab_template' => ' +
  • %s
  • ', + 'panel_template' => ' +
    + %s +
    ', + ]; + +function test() : array +{ + return []; +} + +$fields = [ + 'id' => ['type' => 'INT'], + 'value' => ['type' => 'VARCHAR'], + ]; + +get_current_screen()->add_help_tab( [ + 'id' => << false]; + +$x = [ + 'xxxx' => [ + 'aaaaaaaaaa' => 'ccccccccccc', + 'bbbbbbbb' => false, + ], + ]; + +$foo = [ + 'foo' => [ + 'bar1' => 1, + 'bar2' => 1, + 'bar3' => 1, + 'bar4' => 1, + 'bar5' => 1, + ], + ]; + +$foo = [ + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], ['notverified', 'unverified'], true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), + ]; + + +$foo = foo( + [ + // comment + ] +); + +$foo = [ + << lorem( + 1 + ), + 2 => 2, +]; + +$foo = [ + 'тип' => 'авто', + 'цвет' => 'синий', + ]; + +$paths = [ + Init::ROOT_DIR.'/тип' => 'авто', + Init::ROOT_DIR.'/цвет' => 'синий', + ]; + +$foo = [<< fn() => return 1, + 'bb' => fn() => return 2, + 'ccc' => ( true ) ? + fn() => return 1 : + fn() => return 2, + ]; + +$array = [ + 1 => '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', + ]; + +$foo = [ + $this->fn => 'value', + $foo->fn => 'value', + ]; + +[ + $a, + $b, + $c, +]; + +[ + 'a' => $a, + 'b' => $b, + 'c' => $c, +]; + +[ + static function() { + return null; + }, + (array) [], + (bool) [], + (double) [], + (int) [], + (object) [], + (string) [], + (unset) [], +]; + +[ + 'foo', + 'bar' + // This is a non-fixable error. + , +]; + +yield [ + static fn () : string => '', + ]; + +yield [ + static fn () : string => '', + ]; + +$foo = [ + 'foo' => match ($anything) { + 'foo' => 'bar', + default => null, + }, + ]; + +// Intentional syntax error. +$a = [ + 'a' => + ]; + +// Safeguard correct errors for key/no key when PHP 7.4+ array unpacking is encountered. +$x = [ + ...$a, + 'foo' => 'bar', + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + ]; + +$x = [ + ...$a, + 'foo' => 'bar', // OK. + 'bar', // NoKeySpecified Error (based on second entry). + ]; + +$x = [ + ...$a, + 'bar', // OK. + 'foo' => 'bar', // KeySpecified Error (based on second entry). + ]; + +$x = [ + 'foo' => 'bar', + ...$a, + 'baz' => 'bar', + 'bar', // NoKeySpecified Error (based on first entry). + ]; + +$x = [ + 'bar', + ...$a, + 'bar', + 'baz' => 'bar', // KeySpecified (based on first entry). + ]; + + $x = + [ + 'a', + 'b', + ]; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.php new file mode 100644 index 0000000..03a4044 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Arrays/ArrayDeclarationUnitTest.php @@ -0,0 +1,251 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Arrays; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ArrayDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayDeclarationSniff + */ +class ArrayDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ArrayDeclarationUnitTest.1.inc': + return [ + 2 => 1, + 8 => 2, + 10 => 2, + 22 => 1, + 23 => 2, + 24 => 2, + 25 => 1, + 31 => 2, + 35 => 1, + 36 => 2, + 41 => 1, + 46 => 1, + 47 => 1, + 50 => 1, + 51 => 1, + 53 => 1, + 56 => 1, + 58 => 1, + 61 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 3, + 70 => 1, + 76 => 2, + 77 => 1, + 78 => 7, + 79 => 2, + 81 => 2, + 82 => 4, + 87 => 1, + 88 => 1, + 92 => 1, + 97 => 1, + 100 => 1, + 101 => 1, + 102 => 1, + 105 => 1, + 106 => 1, + 107 => 1, + 125 => 1, + 126 => 1, + 141 => 1, + 144 => 1, + 146 => 1, + 148 => 1, + 151 => 1, + 157 => 1, + 173 => 1, + 174 => 3, + 179 => 1, + 182 => 1, + 188 => 1, + 207 => 1, + 212 => 2, + 214 => 1, + 218 => 2, + 219 => 2, + 223 => 1, + 255 => 1, + 294 => 1, + 295 => 1, + 296 => 1, + 311 => 1, + 317 => 1, + 339 => 2, + 348 => 2, + 352 => 2, + 355 => 3, + 358 => 3, + 359 => 2, + 360 => 1, + 362 => 1, + 363 => 2, + 364 => 1, + 365 => 2, + 366 => 2, + 367 => 2, + 368 => 2, + 369 => 1, + 370 => 1, + 383 => 1, + 394 => 1, + 400 => 1, + 406 => 1, + 441 => 1, + 444 => 2, + 445 => 2, + 447 => 2, + 448 => 3, + 467 => 1, + 471 => 1, + 472 => 1, + 510 => 1, + 516 => 1, + 523 => 1, + 530 => 1, + 537 => 1, + ]; + case 'ArrayDeclarationUnitTest.2.inc': + return [ + 2 => 1, + 10 => 1, + 23 => 2, + 24 => 2, + 25 => 1, + 31 => 2, + 36 => 2, + 41 => 1, + 46 => 1, + 47 => 1, + 51 => 1, + 53 => 1, + 56 => 1, + 61 => 1, + 63 => 1, + 64 => 1, + 65 => 1, + 66 => 2, + 70 => 1, + 76 => 1, + 77 => 1, + 78 => 7, + 79 => 2, + 81 => 2, + 82 => 4, + 87 => 1, + 88 => 1, + 92 => 1, + 97 => 1, + 100 => 1, + 101 => 1, + 102 => 1, + 105 => 1, + 106 => 1, + 107 => 1, + 125 => 1, + 126 => 1, + 141 => 1, + 144 => 1, + 146 => 1, + 148 => 1, + 151 => 1, + 157 => 1, + 173 => 1, + 174 => 3, + 179 => 1, + 190 => 1, + 191 => 1, + 192 => 1, + 207 => 1, + 210 => 1, + 211 => 1, + 215 => 1, + 247 => 1, + 286 => 1, + 287 => 1, + 288 => 1, + 303 => 1, + 309 => 1, + 331 => 2, + 345 => 3, + 348 => 3, + 349 => 2, + 350 => 1, + 352 => 2, + 353 => 2, + 354 => 2, + 355 => 2, + 356 => 2, + 357 => 1, + 358 => 1, + 372 => 1, + 383 => 1, + 389 => 1, + 395 => 1, + 430 => 1, + 433 => 2, + 434 => 2, + 436 => 2, + 437 => 3, + 456 => 1, + 460 => 1, + 461 => 1, + 499 => 1, + 505 => 1, + 512 => 1, + 519 => 1, + 526 => 1, + ]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css new file mode 100644 index 0000000..39abce2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css @@ -0,0 +1,81 @@ +.my-style { +} + + +.my-style { +} + +/* Comment */ + +.my-style { +} + + +/* Comment */ + +.my-style { + float: left; + +} + +.AssetLineageWidgetType-item { + color: #CCC; +} + +/*.AssetLineageWidgetType-item2 .selected, +.AssetLineageWidgetType-item .selected { +}*/ + +.AssetLineageWidgetType-item.selected { +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } +} + +.GUITextBox.container:after {} + +@media screen and (max-device-width: 769px) { + .no-blank-line-after { + } + .no-blank-line-after-second-def { + } .my-style { + } + + .no-blank-line-and-trailing-comment { + } /* end long class */ + .too-many-blank-lines-and-trailing-comment-extra-whitespace-after-brace { + } /* end long class */ + + + + .has-blank-line-and-trailing-comment { + } /* end long class */ + + .no-blank-line-and-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + .too-many-blank-lines-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + + + + .has-blank-line-and-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%;}} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css.fixed new file mode 100644 index 0000000..ca77e83 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.css.fixed @@ -0,0 +1,85 @@ +.my-style { +} + +.my-style { +} + +/* Comment */ + +.my-style { +} + +/* Comment */ + +.my-style { + float: left; + +} + +.AssetLineageWidgetType-item { + color: #CCC; +} + +/*.AssetLineageWidgetType-item2 .selected, +.AssetLineageWidgetType-item .selected { +}*/ + +.AssetLineageWidgetType-item.selected { +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +.GUITextBox.container:after { +} + +@media screen and (max-device-width: 769px) { + .no-blank-line-after { + } + + .no-blank-line-after-second-def { + } + +.my-style { + } + + .no-blank-line-and-trailing-comment { + } /* end long class */ + + .too-many-blank-lines-and-trailing-comment-extra-whitespace-after-brace { + } /* end long class */ + + .has-blank-line-and-trailing-comment { + } /* end long class */ + + .no-blank-line-and-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + + .too-many-blank-lines-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + + .has-blank-line-and-annotation { + } /* phpcs:ignore Standard.Cat.SniffName -- for reasons */ + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; +} + +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.php new file mode 100644 index 0000000..af2f8db --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionClosingBraceSpaceUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDefinitionClosingBraceSpace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ClassDefinitionClosingBraceSpaceSniff + */ +class ClassDefinitionClosingBraceSpaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 11 => 1, + 44 => 1, + 47 => 1, + 51 => 1, + 53 => 1, + 57 => 1, + 59 => 1, + 67 => 1, + 69 => 1, + 81 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.css new file mode 100644 index 0000000..6496cb8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.css @@ -0,0 +1,66 @@ +.AssetListingEditWidgetType-BottomPanel select, +#EditEditingModeWidgetType-assetEditor-filters-assetTypes-addNew { + float: left; +} + +.AssetListingEditWidgetType-BottomPanel select, + +#EditEditingModeWidgetType-assetEditor-filters-assetTypes-addNew { + float: left; +} + +.AssetListingEditWidgetType-BottomPanel select, +/*.AssetListingEditWidgetType-BottomPanel ul,*/ +#EditEditingModeWidgetType-assetEditor-filters-assetTypes-addNew { + float: left; +} + +.AssetListingEditWidgetType-BottomPanel select, + +.AssetListingEditWidgetType-BottomPanel ul, +#EditEditingModeWidgetType-assetEditor-filters-assetTypes-addNew { + float: left; +} + +#SuperUsersSystemConfigScreen-table { + display: block; + left: 50%; + margin-left: -500px; + margin-top: 180px; + position: relative; + width: 1000px; +} + +/** + * More styles below here. + */ + +td.TableWidgetType-header.TableWidgetType-header-lastLogin, +td.TableWidgetType-header.TableWidgetType-header-remove, +td.TableWidgetType-header.TableWidgetType-header-email, +td.TableWidgetType-header.TableWidgetType-header-userName { + background: url(images/ScreenImages/table_header_bg.png) repeat-x; + border-top: 1px solid #D4D4D4; + color: #787878; + height: 33px; + padding-left: 12px; + width: 150px; +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + padding: 20px; + margin: 40px; + } +} + +.foo +{ + border: none; +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.php new file mode 100644 index 0000000..89c21f3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionNameSpacingUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDefinitionNameSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ClassDefinitionNameSpacingSniff + */ +class ClassDefinitionNameSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 19 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css new file mode 100644 index 0000000..98c8fa5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css @@ -0,0 +1,108 @@ +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title{ + float: left; +} +.HelpWidgetType-new-bug-title { + + float: left; +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + + + + header #logo img { + max-width: 100%; + } + +} + +.GUITextBox.container:after {} + +.single-line {float: left;} + +#opening-brace-on-different-line + + +{ + color: #FFFFFF; +} + +#opening-brace-on-different-line-and-inline-style + + +{color: #FFFFFF;} + +@media screen and (max-device-width: 769px) { .everything-on-one-line { float: left; } } + +/* Document handling of comments in various places */ +.no-space-before-opening-with-comment /* comment*/{ + float: left; +} + +.space-before-opening-with-comment-on-next-line +/* comment*/ { + float: left; +} + +#opening-brace-on-different-line-with-comment-between +/*comment*/ +{ + padding: 0; +} + +.single-line-with-comment { /* comment*/ float: left; } + +.multi-line-with-trailing-comment { /* comment*/ + float: left; +} + + +@media screen and (max-device-width: 769px) { + /*comment*/ + .comment-line-after-nesting-class-opening { + } +} + +@media screen and (max-device-width: 769px) { + + /*comment*/ + .blank-line-and-comment-line-after-nesting-class-opening { + } +} + +@media screen and (max-device-width: 769px) { + + + + /* phpcs:ignore Standard.Category.Sniffname -- for reasons */ + .blank-line-and-annotation-after-nesting-class-opening { + } +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css.fixed new file mode 100644 index 0000000..b3f48a5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.css.fixed @@ -0,0 +1,106 @@ +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + + float: left; +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + +} + +.GUITextBox.container:after { +} + +.single-line { +float: left;} + +#opening-brace-on-different-line { + color: #FFFFFF; +} + +#opening-brace-on-different-line-and-inline-style { +color: #FFFFFF;} + +@media screen and (max-device-width: 769px) { + +.everything-on-one-line { +float: left; } } + +/* Document handling of comments in various places */ +.no-space-before-opening-with-comment /* comment*/ { + float: left; +} + +.space-before-opening-with-comment-on-next-line +/* comment*/ { + float: left; +} + +#opening-brace-on-different-line-with-comment-between +/*comment*/ { + padding: 0; +} + +.single-line-with-comment { +/* comment*/ float: left; } + +.multi-line-with-trailing-comment { /* comment*/ + float: left; +} + + +@media screen and (max-device-width: 769px) { + + /*comment*/ + .comment-line-after-nesting-class-opening { + } +} + +@media screen and (max-device-width: 769px) { + + /*comment*/ + .blank-line-and-comment-line-after-nesting-class-opening { + } +} + +@media screen and (max-device-width: 769px) { + + /* phpcs:ignore Standard.Category.Sniffname -- for reasons */ + .blank-line-and-annotation-after-nesting-class-opening { + } +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.php new file mode 100644 index 0000000..6e9faeb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ClassDefinitionOpeningBraceSpaceUnitTest.php @@ -0,0 +1,69 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDefinitionOpeningBraceSpace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ClassDefinitionOpeningBraceSpaceSniff + */ +class ClassDefinitionOpeningBraceSpaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 7 => 1, + 10 => 1, + 26 => 1, + 33 => 1, + 43 => 1, + 45 => 1, + 50 => 1, + 57 => 2, + 59 => 2, + 62 => 1, + 73 => 1, + 77 => 1, + 84 => 1, + 97 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css new file mode 100644 index 0000000..391bc85 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css @@ -0,0 +1,42 @@ +body { +font-family: Arial, Helvetica, sans-serif; +margin : 40px 0 0 0; +padding : 0; +background: #8FB7DB url(diag_lines_bg.gif) top left; +margin-top: +10px; +margin-bottom: +0px; +} + +.TableWidgetType .recover:hover { + background-color: #FFF; +} + +#clearCache-settings:rootNodes-list_0 { + border-top: none; +} + +.LookupEditScreenWidgetType-urls a, .LookupEditScreenWidgetType-urls a:visited { + text-decoration: none; + color: #444; +} + +/* checking embedded PHP */ +li { + background:url(/images//bullet.gif) left px no-repeat; + margin:0px; + padding-left:10px; + margin-bottom:px; + margin-top: px; + line-height:13px; + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#2e62a8, endColorstr=#123363); +} + +/* Empty style defs. */ +.p { + margin:; + margin-right: + margin-left: 10px; + float:/* Some comment. */ ; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css.fixed new file mode 100644 index 0000000..e68bddc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.css.fixed @@ -0,0 +1,40 @@ +body { +font-family: Arial, Helvetica, sans-serif; +margin: 40px 0 0 0; +padding: 0; +background: #8FB7DB url(diag_lines_bg.gif) top left; +margin-top: 10px; +margin-bottom: 0px; +} + +.TableWidgetType .recover:hover { + background-color: #FFF; +} + +#clearCache-settings:rootNodes-list_0 { + border-top: none; +} + +.LookupEditScreenWidgetType-urls a, .LookupEditScreenWidgetType-urls a:visited { + text-decoration: none; + color: #444; +} + +/* checking embedded PHP */ +li { + background: url(/images//bullet.gif) left px no-repeat; + margin: 0px; + padding-left: 10px; + margin-bottom: px; + margin-top: px; + line-height: 13px; + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#2e62a8, endColorstr=#123363); +} + +/* Empty style defs. */ +.p { + margin:; + margin-right: + margin-left: 10px; + float: /* Some comment. */ ; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.php new file mode 100644 index 0000000..8c79d0c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColonSpacingUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ColonSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ColonSpacingSniff + */ +class ColonSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 4 => 2, + 5 => 1, + 6 => 1, + 8 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 32 => 1, + 41 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css new file mode 100644 index 0000000..2dfd22a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css @@ -0,0 +1,16 @@ +#title-bar-bottom-right { + background-color: #333333; + padding: 10px; + border-bottom: 1px dotted #F0F0F0; + border-top: 1px dotted #FF00FF; + background: #08f7db url(diag_lines_bg.gif) top left; + + /* The sniff only deals with HEX colours. */ + color: DarkSlateGray; + background-color: rgb(255, 0, 0); + background-color: rgba(0, 0, 255, 0.3); + background-color: hsl(120, 100%, 50%); +} + +#add-new-comment { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css.fixed new file mode 100644 index 0000000..039209d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.css.fixed @@ -0,0 +1,16 @@ +#title-bar-bottom-right { + background-color: #333; + padding: 10px; + border-bottom: 1px dotted #F0F0F0; + border-top: 1px dotted #F0F; + background: #08F7DB url(diag_lines_bg.gif) top left; + + /* The sniff only deals with HEX colours. */ + color: DarkSlateGray; + background-color: rgb(255, 0, 0); + background-color: rgba(0, 0, 255, 0.3); + background-color: hsl(120, 100%, 50%); +} + +#add-new-comment { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.php new file mode 100644 index 0000000..100386a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ColourDefinitionUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ColourDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ColourDefinitionSniff + */ +class ColourDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 5 => 1, + 6 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css new file mode 100644 index 0000000..4c11bea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css @@ -0,0 +1,17 @@ +.SettingsTabPaneWidgetType-tab-mid { + background: transparent url(tab_inact_mid.png) repeat-x; + height: 100%;float: left; + line-height: -25px; + cursor: pointer; margin: 10px; float: right; +} + +/* testing embedded PHP */ +li { + background:url(/images//bullet.gif) left px no-repeat; margin:0px; padding-left:10px; margin-bottom:px; line-height:13px; + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#2e62a8, endColorstr=#123363); +} + +/* Document handling of comments and annotations. */ +div#annotations {-webkit-tap-highlight-color:transparent;/* phpcs:disable Standard.Cat.SniffName */-webkit-touch-callout:none;/*phpcs:enable*/-webkit-user-select:none;} + +div#comments {height:100%;/*comment*/width:100%;} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css.fixed new file mode 100644 index 0000000..93a7815 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.css.fixed @@ -0,0 +1,27 @@ +.SettingsTabPaneWidgetType-tab-mid { + background: transparent url(tab_inact_mid.png) repeat-x; + height: 100%; +float: left; + line-height: -25px; + cursor: pointer; +margin: 10px; +float: right; +} + +/* testing embedded PHP */ +li { + background:url(/images//bullet.gif) left px no-repeat; +margin:0px; +padding-left:10px; +margin-bottom:px; +line-height:13px; + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#2e62a8, endColorstr=#123363); +} + +/* Document handling of comments and annotations. */ +div#annotations {-webkit-tap-highlight-color:transparent;/* phpcs:disable Standard.Cat.SniffName */ +-webkit-touch-callout:none;/*phpcs:enable*/ +-webkit-user-select:none;} + +div#comments {height:100%;/*comment*/ +width:100%;} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.php new file mode 100644 index 0000000..b9efc5d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DisallowMultipleStyleDefinitionsUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowMultipleStyleDefinitions sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\DisallowMultipleStyleDefinitionsSniff + */ +class DisallowMultipleStyleDefinitionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 2, + 10 => 4, + 15 => 2, + 17 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.css new file mode 100644 index 0000000..8ac9501 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.css @@ -0,0 +1,103 @@ +.AssetLineageWidgetType-item { + color: #FFF; +} + +.AssetLineageWidgetType-title { + color: #CCC; +} + +.AssetLineageWidgetType-item { + color: #CCC; +} + +.AssetLineageWidgetType-item .selected { +} + +.AssetLineageWidgetType-item.selected { +} + +#Blah .AssetLineageWidgetType-item { +} + +#X.selected, +.AssetLineageWidgetType-item { +} + +.MyClass, .YourClass { +} + +.YourClass, .MyClass { +} + +.YourClass, .MyClass, .OurClass { +} + + +.ClassAtTopOfMediaBlock { +} + +@media print { + .ClassAtTopOfMediaBlock { + } + + .ClassInMultipleMediaBlocks { + } +} + +.ClassNotAtTopOfMediaBlock { +} + +@media handheld { + .SameClassInMediaBlock { + } + + .ClassNotAtTopOfMediaBlock { + } + + .SameClassInMediaBlock { + } +} + +@media braille { + .PlaceholderClass { + } + + .ClassNotAtTopOfMediaBlock { + } + + .ClassInMultipleMediaBlocks { + } +} + +.foo /* any comment */ +{ color: red; } + +/* print comment */ +@media print { + /* comment1 */ + td { + } + + /* comment2 */ + img { + } + + /* comment3 */ + td { + } +} + +@media handheld /* handheld comment */ +{ + td /* comment1 */ + { + } + + img /* comment2 */ + { + } + + td /* comment3 */ + { + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.php new file mode 100644 index 0000000..e6d31f3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateClassDefinitionUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DuplicateClassDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\DuplicateClassDefinitionSniff + */ +class DuplicateClassDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 29 => 1, + 57 => 1, + 86 => 1, + 101 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.css new file mode 100644 index 0000000..c9c849f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.css @@ -0,0 +1,27 @@ +.ViperSubToolbar-wrapper { + height: 34px; + left: 0; + position: fixed; + top: 60px; + z-index: 997; + left: 50%; +} + +.expandable { + -moz-transition-property: margin-left, margin-right; + -moz-transition-duration: 0.2s; + -moz-transition-timing-function: ease; + -webkit-transition-property: margin-left, margin-right; + -webkit-transition-duration: 0.2s; + -webkit-transition-timing-function: ease; + z-index: 2; +} + +@media only screen and (max-width: 480px) { + header nav.meta a { display: none; } + header nav.meta a.search { display: block; } +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.php new file mode 100644 index 0000000..2b6e04f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/DuplicateStyleDefinitionUnitTest.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DuplicateStyleDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\DuplicateStyleDefinitionSniff + */ +class DuplicateStyleDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [7 => 1]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.css new file mode 100644 index 0000000..801dcda --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.css @@ -0,0 +1,15 @@ +.HelpWidgetType-new-bug-title {} +.HelpWidgetType-new-bug-title { +} +.HelpWidgetType-new-bug-title { + +} +.HelpWidgetType-new-bug-title { + +} +.HelpWidgetType-new-bug-title { + /* Nothing to see here */ +} +.HelpWidgetType-new-bug-title { + float: left; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.php new file mode 100644 index 0000000..767265d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyClassDefinitionUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EmptyClassDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\EmptyClassDefinitionSniff + */ +class EmptyClassDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 1 => 1, + 2 => 1, + 4 => 1, + 7 => 1, + 10 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.css new file mode 100644 index 0000000..24910b7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.css @@ -0,0 +1,11 @@ +#MetadataAdminScreen-addField-fieldType { + margin-left: 10px; + margin-right: + float: ; +} + +#MetadataAdminScreen-addField-fieldType li { + margin-right: /* @todo */ + margin-left: 10px; + float: /* Some comment. */ ; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.php new file mode 100644 index 0000000..cd591e8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/EmptyStyleDefinitionUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EmptyStyleDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\EmptyStyleDefinitionSniff + */ +class EmptyStyleDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 4 => 1, + 8 => 1, + 10 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css new file mode 100644 index 0000000..dbd5487 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css @@ -0,0 +1,18 @@ +#add-new-comment { + -moz-border-radius: 1px; + -webkit-border-radius: 1px; + border-radius: 1px; + + -moz-border-radius-topleft: 1px; + -moz-border-radius-topright: 1px; + -moz-border-radius-bottomright: 1px; + -moz-border-radius-bottomleft: 1px; + border-top-left-radius: 1px; + border-top-right-radius: 1px; + border-bottom-right-radius: 1px; + border-bottom-left-radius: 1px; + + -moz-box-shadow: 1px; + -webkit-box-shadow: 1px; + box-shadow: 1px; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css.fixed new file mode 100644 index 0000000..a8ea270 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.css.fixed @@ -0,0 +1,18 @@ +#add-new-comment { + border-radius: 1px; + border-radius: 1px; + border-radius: 1px; + + border-top-left-radius: 1px; + border-top-right-radius: 1px; + border-bottom-right-radius: 1px; + border-bottom-left-radius: 1px; + border-top-left-radius: 1px; + border-top-right-radius: 1px; + border-bottom-right-radius: 1px; + border-bottom-left-radius: 1px; + + box-shadow: 1px; + box-shadow: 1px; + box-shadow: 1px; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.php new file mode 100644 index 0000000..b212aec --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ForbiddenStylesUnitTest.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ForbiddenStyles sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ForbiddenStylesSniff + */ +class ForbiddenStylesUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 3 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 9 => 1, + 15 => 1, + 16 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css new file mode 100644 index 0000000..216f00e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css @@ -0,0 +1,79 @@ +body { + + font-family: Arial, Helvetica, sans-serif; + margin: 40px 0 0 0; +padding: 0; + background: #8FB7DB url(diag_lines_bg.gif) top left; + +} + +td { + margin: 40px; + + padding: 20px; +} + +/* +#AdminScreenModeWidgetType-tab_pane-containers .TabPaneWidgetType-tab-selected-left { + background: transparent url(images/ScreenImages/tab_on_left.png) no-repeat; +} +#AdminScreenModeWidgetType-tab_pane-containers .TabPaneWidgetType-tab-selected-right { + background: transparent url(images/ScreenImages/tab_on_right.png) no-repeat; +} +*/ + +.GUITextBox.container:after {} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + padding: 20px; + margin: 40px; + } +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + + header #logo img { + min-width: 100%; + } + +} + +td { + margin: 40px; + + padding: 20px; + + +} + +.GUIFileUpload { +/* opacity: 0.25; */ +} + +.foo +{ + border: none; +} + +.mortgage-calculator h2 { + background: #072237; + color: #fff; + font-weight: normal; + height: 50px; + line-height: 50px; + padding: 0 0 0 30px; + } + +.WhitelistCommentIndentationShouldBeIgnored { +/* phpcs:disable Standard.Category.Sniff -- for reasons. */ +} + +/* syntax error */ +--------------------------------------------- */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css.fixed new file mode 100644 index 0000000..1fd128a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.1.css.fixed @@ -0,0 +1,73 @@ +body { + font-family: Arial, Helvetica, sans-serif; + margin: 40px 0 0 0; + padding: 0; + background: #8FB7DB url(diag_lines_bg.gif) top left; +} + +td { + margin: 40px; + padding: 20px; +} + +/* +#AdminScreenModeWidgetType-tab_pane-containers .TabPaneWidgetType-tab-selected-left { + background: transparent url(images/ScreenImages/tab_on_left.png) no-repeat; +} +#AdminScreenModeWidgetType-tab_pane-containers .TabPaneWidgetType-tab-selected-right { + background: transparent url(images/ScreenImages/tab_on_right.png) no-repeat; +} +*/ + +.GUITextBox.container:after {} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + padding: 20px; + margin: 40px; + } +} + +@media screen and (max-device-width: 769px) { + + header #logo img { + max-width: 100%; + } + + header #logo img { + min-width: 100%; + } + +} + +td { + margin: 40px; + padding: 20px; +} + +.GUIFileUpload { +/* opacity: 0.25; */ +} + +.foo +{ + border: none; +} + +.mortgage-calculator h2 { + background: #072237; + color: #fff; + font-weight: normal; + height: 50px; + line-height: 50px; + padding: 0 0 0 30px; +} + +.WhitelistCommentIndentationShouldBeIgnored { +/* phpcs:disable Standard.Category.Sniff -- for reasons. */ +} + +/* syntax error */ +--------------------------------------------- */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.2.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.2.css new file mode 100644 index 0000000..48b22f6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.2.css @@ -0,0 +1,3 @@ +/* Live coding. Has to be the last (only) test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.php new file mode 100644 index 0000000..0f4fb5d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/IndentationUnitTest.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the Indentation sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\IndentationSniff + */ +class IndentationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'IndentationUnitTest.1.css': + return [ + 2 => 1, + 3 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 12 => 1, + 30 => 1, + 32 => 1, + 50 => 1, + 52 => 1, + 53 => 1, + 66 => 1, + 67 => 1, + 68 => 1, + 69 => 1, + 70 => 1, + 71 => 1, + 72 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.css new file mode 100644 index 0000000..d0f2982 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.css @@ -0,0 +1,14 @@ +.SettingsTabPaneWidgetType-tab-mid { + font-family: Arial; + Font-Family: arial; + background-color: #DA9393; + BACKGROUND-IMAGE: URL(Warning_Close.png); +} + +@media screen and (max-device-width: 769px) { + + .SettingsTabPaneWidgetType-tab-mid { + Font-Family: arial; + filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#2e62a8, endColorstr=#123363); + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.php new file mode 100644 index 0000000..ed2ac53 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/LowercaseStyleDefinitionUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowercaseStyleDefinition sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\LowercaseStyleDefinitionSniff + */ +class LowercaseStyleDefinitionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 3 => 1, + 5 => 2, + 11 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.css new file mode 100644 index 0000000..6c947e5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.css @@ -0,0 +1,21 @@ +.my-style { + margin-right 15px; + float: left; + margin-left 15px; + margin-top: 15px; + margin-bottom 15px; +} + +@media screen and (max-device-width: 769px) { + header #logo img { + max-width: 100%; + margin-bottom 15px; + } +} + +#foo { background-color: #FF0000; +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.php new file mode 100644 index 0000000..c0ef173 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/MissingColonUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MissingColon sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\MissingColonSniff + */ +class MissingColonUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 4 => 1, + 6 => 1, + 12 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.css new file mode 100644 index 0000000..05637a6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.css @@ -0,0 +1,25 @@ +#red { + background-color: red; +} + +.red { + border-bottom: 1px dotted black; + border-top: 1px dotted gray; +} + +#red.yellow { + background: yellow url(diag_lines_bg.gif) top left; + text-shadow: 0 1px 0 white; +} + +.something--white { + border: 0; +} + +.something--------------white { + border: 0; +} + +.-white { + border: 0; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.php new file mode 100644 index 0000000..9a2e25f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/NamedColoursUnitTest.php @@ -0,0 +1,59 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the NamedColours sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\NamedColoursSniff + */ +class NamedColoursUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 6 => 1, + 7 => 1, + 11 => 1, + 12 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css new file mode 100644 index 0000000..c656c78 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css @@ -0,0 +1,35 @@ +.my-style { + opacity: 0; + opacity: 0.0; + opacity: 1; + opacity: 1.0; + opacity: 1.5; + opacity: .5; + opacity: 0.5; + opacity: 2; + opacity: -1; + opacity: 0.55; +} + +div { + font-size: 1.2em; + background: linear-gradient(to bottom, #00F, #0F0) repeat scroll 50% 50% #EEE; + min-width: 250px; + max-width: 100%; + padding-bottom: 50px; + box-shadow: 2px -3px 3px rgba(100, 100, 100, 0.33); + border-left: 1px solid #000; + border-right: 1px solid #000; + border-top: 1px solid #000; + border-bottom: 1px dotted #000; + background: url(../1/2/3/4-5-6_7_100x100.png) repeat scroll 50% 50% #EEE; + opacity: -1; +} + +.my-commented-style { + opacity: /*comment*/ 0; + opacity: /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ + 0.0; + opacity: /*comment*/ 1.0; + opacity: /*comment*/ .5; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css.fixed new file mode 100644 index 0000000..257e41a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.css.fixed @@ -0,0 +1,35 @@ +.my-style { + opacity: 0; + opacity: 0; + opacity: 1; + opacity: 1; + opacity: 1.5; + opacity: 0.5; + opacity: 0.5; + opacity: 2; + opacity: -1; + opacity: 0.55; +} + +div { + font-size: 1.2em; + background: linear-gradient(to bottom, #00F, #0F0) repeat scroll 50% 50% #EEE; + min-width: 250px; + max-width: 100%; + padding-bottom: 50px; + box-shadow: 2px -3px 3px rgba(100, 100, 100, 0.33); + border-left: 1px solid #000; + border-right: 1px solid #000; + border-top: 1px solid #000; + border-bottom: 1px dotted #000; + background: url(../1/2/3/4-5-6_7_100x100.png) repeat scroll 50% 50% #EEE; + opacity: -1; +} + +.my-commented-style { + opacity: /*comment*/ 0; + opacity: /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ + 0; + opacity: /*comment*/ 1; + opacity: /*comment*/ 0.5; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.php new file mode 100644 index 0000000..c0454a8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/OpacityUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the Opacity sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\OpacitySniff + */ +class OpacityUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 26 => 1, + 32 => 1, + 33 => 1, + 34 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css new file mode 100644 index 0000000..3ccb162 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css @@ -0,0 +1,61 @@ +.HelpWidgetType-new-bug-title { + width: 308px + float: left; +} + +#MetadataAdminScreen-addField-add { + float: left ; +} + +.TableWidgetType .recover:hover { + background-color: #FFF; +} + +#clearCache-settings:rootNodes-list_0 { + border-top: none; +} + +.HelpWidgetType-list { + list-style-image: url(); +} + +@media (min-width: 320px) and (max-width: 961px) { + .tooltipsrt:hover span.tltp, + .tooltipstp:hover span.tltp { + visibility: hidden; + } +} + +#single-line-multi-statement-no-semicolon { + padding: 0 border: 20; +} + +#multi-line-style-no-semicolon { + padding: 0 /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ + border: + 20 + margin: + 0px /* top */ + 10px /* right + left */ +} + +#multi-line-style-whitespace { + padding: 0 /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ ; + border: + 20 ; + margin: + 10px /* top */ + 0px /* right + left */ + + + ; +} + +.allow-for-star-hack { + cursor: pointer; + *cursor: hand; +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css.fixed new file mode 100644 index 0000000..7efef58 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.css.fixed @@ -0,0 +1,58 @@ +.HelpWidgetType-new-bug-title { + width: 308px + float: left; +} + +#MetadataAdminScreen-addField-add { + float: left; +} + +.TableWidgetType .recover:hover { + background-color: #FFF; +} + +#clearCache-settings:rootNodes-list_0 { + border-top: none; +} + +.HelpWidgetType-list { + list-style-image: url(); +} + +@media (min-width: 320px) and (max-width: 961px) { + .tooltipsrt:hover span.tltp, + .tooltipstp:hover span.tltp { + visibility: hidden; + } +} + +#single-line-multi-statement-no-semicolon { + padding: 0 border: 20; +} + +#multi-line-style-no-semicolon { + padding: 0 /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ + border: + 20 + margin: + 0px /* top */ + 10px /* right + left */ +} + +#multi-line-style-whitespace { + padding: 0; /* phpcs:ignore Standard.Cat.Sniff -- for reasons */ + border: + 20; + margin: + 10px /* top */ + 0px; /* right + left */ +} + +.allow-for-star-hack { + cursor: pointer; + *cursor: hand; +} + +/* Live coding. Has to be the last test in the file. */ +.intentional-parse-error { + float: left diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.php new file mode 100644 index 0000000..334fc7b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/SemicolonSpacingUnitTest.php @@ -0,0 +1,63 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SemicolonSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\SemicolonSpacingSniff + */ +class SemicolonSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 7 => 1, + 30 => 1, + 34 => 1, + 36 => 1, + 39 => 1, + 43 => 1, + 45 => 1, + 48 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css new file mode 100644 index 0000000..cfc4503 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css @@ -0,0 +1,45 @@ +#add-new-comment { + background-color: #333333; + padding: 10px; + border-bottom: 1px dotted #F0F0F0; + border-top: 1px dotted #FF00FF; + background: #8fb7db url(diag_lines_bg.gif) top left; + tab-size: 1; + margin: 8px 8px 8px 8px; + margin: 8px 8px; + margin: 0 0 0 0; + margin: 0 8px 0 8px; + margin: 8px 4px 8px 4px; + margin: 8px 4% 8px 4%; + margin: 6px 2px 9px 2px; + margin: 6px 2px 9px; + border-radius: 2px 2px 2px 2px !important; + border-width: 2px 2px 2px 2px; + border-width: 1px 2px 2px 4px; + margin: 97px auto 0 auto; + text-shadow: 0 1px 0 #fff; + border-width: + 2px + 4px + 2px + 4px; + + /* These are style names excluded from this rule. */ + background-position: 0 0; + box-shadow: 2px 2px 2px 2px; + transform-origin: 0 110% 0; + + /* Sizes with comments between them will be ignored for the purposes of this sniff. */ + margin: 8px /*top*/ 8px /*right*/ 8px /*bottom*/ 8px /*left*/; + + /* Same with PHPCS annotations. */ + border-width: + 2px /* phpcs:ignore Standard.Category.SniffName -- for reasons */ + 4px + 2px /* phpcs:disable Standard.Category.SniffName -- for reasons */ + 4px; +} + +/* Intentional parse error. Live coding resilience. This has to be the last test in the file. */ +#live-coding { + margin: 8px 8px 8px 8px diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css.fixed new file mode 100644 index 0000000..3472cb1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.css.fixed @@ -0,0 +1,41 @@ +#add-new-comment { + background-color: #333333; + padding: 10px; + border-bottom: 1px dotted #F0F0F0; + border-top: 1px dotted #FF00FF; + background: #8fb7db url(diag_lines_bg.gif) top left; + tab-size: 1; + margin: 8px; + margin: 8px; + margin: 0; + margin: 0 8px; + margin: 8px 4px; + margin: 8px 4%; + margin: 6px 2px 9px 2px; + margin: 6px 2px 9px 2px; + border-radius: 2px !important; + border-width: 2px; + border-width: 1px 2px 2px 4px; + margin: 97px auto 0 auto; + text-shadow: 0 1px 0 #fff; + border-width: 2px 4px; + + /* These are style names excluded from this rule. */ + background-position: 0 0; + box-shadow: 2px 2px 2px 2px; + transform-origin: 0 110% 0; + + /* Sizes with comments between them will be ignored for the purposes of this sniff. */ + margin: 8px /*top*/ 8px /*right*/ 8px /*bottom*/ 8px /*left*/; + + /* Same with PHPCS annotations. */ + border-width: + 2px /* phpcs:ignore Standard.Category.SniffName -- for reasons */ + 4px + 2px /* phpcs:disable Standard.Category.SniffName -- for reasons */ + 4px; +} + +/* Intentional parse error. Live coding resilience. This has to be the last test in the file. */ +#live-coding { + margin: 8px 8px 8px 8px diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.php new file mode 100644 index 0000000..9f5a3bb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/CSS/ShorthandSizeUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\CSS; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ShorthandSize sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS\ShorthandSizeSniff + */ +class ShorthandSizeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 8 => 1, + 9 => 1, + 10 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 15 => 1, + 16 => 1, + 17 => 1, + 21 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassDeclarationUnitTest.inc new file mode 100644 index 0000000..2af42d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassDeclarationUnitTest.inc @@ -0,0 +1,130 @@ + + + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassDeclarationSniff + */ +class ClassDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 6 => 1, + 10 => 1, + 15 => 2, + 18 => 1, + 22 => 4, + 23 => 4, + 24 => 4, + 27 => 2, + 30 => 2, + 34 => 1, + 35 => 1, + 39 => 1, + 42 => 1, + 45 => 1, + 48 => 1, + 50 => 2, + 51 => 1, + 55 => 1, + 59 => 4, + 63 => 1, + 65 => 1, + 69 => 3, + 74 => 2, + 77 => 1, + 80 => 1, + 85 => 3, + 89 => 1, + 92 => 1, + 97 => 1, + 108 => 1, + 114 => 1, + 116 => 1, + 118 => 1, + 121 => 1, + 124 => 2, + 128 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.inc new file mode 100644 index 0000000..8b5a5aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.inc @@ -0,0 +1,45 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.php new file mode 100644 index 0000000..1d64fc5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ClassFileNameUnitTest.php @@ -0,0 +1,82 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassFileName sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassFileNameSniff + */ +class ClassFileNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + 16 => 1, + 17 => 1, + 18 => 1, + 19 => 1, + 20 => 1, + 21 => 1, + 22 => 1, + 23 => 1, + 27 => 1, + 28 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 32 => 1, + 33 => 1, + 34 => 1, + 35 => 1, + 36 => 1, + 37 => 1, + 38 => 1, + 39 => 1, + 40 => 1, + 41 => 1, + 42 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.js new file mode 100644 index 0000000..04126f8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.js @@ -0,0 +1,45 @@ +var x = { + abc: 1, + zyz: 2, + abc: 5, + mno: { + abc: 4 + }, + abc: 5 + + this.request({ + action: 'getSubmissions' + }); + + this.request({ + action: 'deleteSubmission' + }); +} + + +LinkingEditScreenWidgetType.prototype = { + + _addDeleteButtonEvent: function(parentid) + { + var params = { + screen: 'LinkingEditScreenWidget', + assetid: self.assetid, + parentid: parentid, + assetid: parentid, + op: 'deleteLink' + }; + + }, + + saveDesignEdit: function() + { + var params = { + screen: [this.id, 'Widget'].join(''), + assetid: this.assetid, + changes: dfx.jsonEncode(this.currnetLinksWdgt.getChanges()), + op: 'saveLinkEdit' + }; + + } + +}; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.php new file mode 100644 index 0000000..a1cfd5b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/DuplicatePropertyUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DuplicateProperty sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\DuplicatePropertySniff + */ +class DuplicatePropertyUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 8 => 1, + 28 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/LowercaseClassKeywordsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/LowercaseClassKeywordsUnitTest.inc new file mode 100644 index 0000000..eb72450 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/LowercaseClassKeywordsUnitTest.inc @@ -0,0 +1,14 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowercaseClassKeywords sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\LowercaseClassKeywordsSniff + */ +class LowercaseClassKeywordsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + $errors = [ + 2 => 3, + 3 => 3, + 4 => 1, + 5 => 1, + 6 => 2, + 8 => 1, + 10 => 1, + 11 => 1, + 14 => 1, + ]; + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc new file mode 100644 index 0000000..0a0729a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc @@ -0,0 +1,174 @@ +testResults; + + + // Correct call to self. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = parent::selfMemberReferenceUnitTestFunction(); + + // Incorrect case. + $testResults[] = Self::selfMemberReferenceUnitTestFunction(); + $testResults[] = SELF::selfMemberReferenceUnitTestFunction(); + $testResults[] = SelfMemberReferenceUnitTestExample::selfMemberReferenceUnitTestFunction(); + + + // Incorrect spacing. + $testResults[] = self ::selfMemberReferenceUnitTestFunction(); + $testResults[] = self:: selfMemberReferenceUnitTestFunction(); + $testResults[] = self :: selfMemberReferenceUnitTestFunction(); + + // Remove ALL the newlines + $testResults[] = self + + + + + :: + + + + + selfMemberReferenceUnitTestFunction(); + + } + + + function selfMemberReferenceUnitTestFunction() + { + $this->testCount = $this->testCount + 1; + return $this->testCount; + + } + + +} + + +class MyClass { + + public static function test($value) { + echo "$value\n"; + } + + public static function walk() { + $callback = function($value, $key) { + // This is valid because you can't use self:: in a closure. + MyClass::test($value); + }; + + $array = array(1,2,3); + array_walk($array, $callback); + } +} + +MyClass::walk(); + +class Controller +{ + public function Action() + { + Doctrine\Common\Util\Debug::dump(); + } +} + +class Foo +{ + public static function bar() + { + \Foo::baz(); + } +} + +namespace TYPO3\CMS\Reports; + +class Status { + const NOTICE = -2; + const INFO = -1; + const OK = 0; + const WARNING = 1; + const ERROR = 2; +} + +namespace TYPO3\CMS\Reports\Report\Status; + +class Status implements \TYPO3\CMS\Reports\ReportInterface { + public function getHighestSeverity(array $statusCollection) { + $highestSeverity = \TYPO3\CMS\Reports\Status::NOTICE; + } +} + +namespace Foo; + +class Bar { + + function myFunction() + { + \Foo\Whatever::something(); + \Foo\Bar::something(); + } +} + +namespace Foo\Bar; + +class Baz { + + function myFunction() + { + \Foo\Bar\Whatever::something(); + \Foo\Bar\Baz::something(); + } +} + +class Nested_Anon_Class { + public function getAnonymousClass() { + // Spacing/comments should not cause false negatives for the NotUsed error. + Nested_Anon_Class :: $prop; + Nested_Anon_Class + /* some comment */ + + :: + + // phpcs:ignore Standard.Category.SniffName -- for reasons. + Bar(); + + // Anonymous class is a different scope. + return new class() { + public function nested_function() { + Nested_Anon_Class::$prop; + Nested_Anon_Class::BAR; + } + }; + } +} + +// Test dealing with scoped namespaces. +namespace Foo\Baz { + class BarFoo { + public function foo() { + echo Foo\Baz\BarFoo::$prop; + } + } +} + +// Prevent false negative when namespace has whitespace/comments. +namespace Foo /*comment*/ \ Bah { + class BarFoo { + public function foo() { + echo Foo \ /*comment*/ Bah\BarFoo::$prop; + } + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc.fixed new file mode 100644 index 0000000..f2c1731 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.inc.fixed @@ -0,0 +1,162 @@ +testResults; + + + // Correct call to self. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = parent::selfMemberReferenceUnitTestFunction(); + + // Incorrect case. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + + // Incorrect spacing. + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + // Remove ALL the newlines + $testResults[] = self::selfMemberReferenceUnitTestFunction(); + + } + + + function selfMemberReferenceUnitTestFunction() + { + $this->testCount = $this->testCount + 1; + return $this->testCount; + + } + + +} + + +class MyClass { + + public static function test($value) { + echo "$value\n"; + } + + public static function walk() { + $callback = function($value, $key) { + // This is valid because you can't use self:: in a closure. + MyClass::test($value); + }; + + $array = array(1,2,3); + array_walk($array, $callback); + } +} + +MyClass::walk(); + +class Controller +{ + public function Action() + { + Doctrine\Common\Util\Debug::dump(); + } +} + +class Foo +{ + public static function bar() + { + self::baz(); + } +} + +namespace TYPO3\CMS\Reports; + +class Status { + const NOTICE = -2; + const INFO = -1; + const OK = 0; + const WARNING = 1; + const ERROR = 2; +} + +namespace TYPO3\CMS\Reports\Report\Status; + +class Status implements \TYPO3\CMS\Reports\ReportInterface { + public function getHighestSeverity(array $statusCollection) { + $highestSeverity = \TYPO3\CMS\Reports\Status::NOTICE; + } +} + +namespace Foo; + +class Bar { + + function myFunction() + { + \Foo\Whatever::something(); + self::something(); + } +} + +namespace Foo\Bar; + +class Baz { + + function myFunction() + { + \Foo\Bar\Whatever::something(); + self::something(); + } +} + +class Nested_Anon_Class { + public function getAnonymousClass() { + // Spacing/comments should not cause false negatives for the NotUsed error. + self::$prop; + + /* some comment */ + + self::// phpcs:ignore Standard.Category.SniffName -- for reasons. + Bar(); + + // Anonymous class is a different scope. + return new class() { + public function nested_function() { + Nested_Anon_Class::$prop; + Nested_Anon_Class::BAR; + } + }; + } +} + +// Test dealing with scoped namespaces. +namespace Foo\Baz { + class BarFoo { + public function foo() { + echo self::$prop; + } + } +} + +// Prevent false negative when namespace has whitespace/comments. +namespace Foo /*comment*/ \ Bah { + class BarFoo { + public function foo() { + echo /*comment*/ self::$prop; + } + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.php new file mode 100644 index 0000000..703dff3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/SelfMemberReferenceUnitTest.php @@ -0,0 +1,69 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SelfMemberReference sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\SelfMemberReferenceSniff + */ +class SelfMemberReferenceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 24 => 1, + 25 => 1, + 26 => 1, + 30 => 1, + 31 => 1, + 32 => 2, + 40 => 2, + 92 => 1, + 121 => 1, + 132 => 1, + 139 => 3, + 140 => 1, + 143 => 2, + 162 => 1, + 171 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.inc new file mode 100644 index 0000000..3fe3943 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.inc @@ -0,0 +1,191 @@ +anonymous = new class extends ArrayObject + { + public function __construct() + { + parent::__construct(['a' => 1, 'b' => 2]); + } + }; + } +} + +// Valid interface name. +interface ValidCamelCaseClass extends MyClass {} + + +// Incorrect usage of camel case. +interface invalidCamelCaseClass extends MyClass {} +interface Invalid_Camel_Case_Class_With_Underscores implements MyClass {} + + +// All lowercase. +interface invalidlowercaseclass extends MyClass {} +interface invalid_lowercase_class_with_underscores extends MyClass {} + + +// All uppercase. +interface VALIDUPPERCASECLASS extends MyClass {} +interface INVALID_UPPERCASE_CLASS_WITH_UNDERSCORES extends MyClass {} + + +// Mix camel case with uppercase. +interface ValidCamelCaseClassWithUPPERCASE extends MyClass {} + + +// Usage of numeric characters. +interface ValidCamelCaseClassWith1Number extends MyClass {} +interface ValidCamelCaseClassWith12345Numbers extends MyClass {} +interface 5InvalidCamelCaseClassStartingWithNumber extends MyClass {} +interface ValidCamelCaseClassEndingWithNumber5 extends MyClass {} +interface 12345 extends MyClass {} + +interface Testing{} + +interface Base +{ + protected $anonymous; + + public function __construct(); +} + + +// Valid trait name. +trait ValidCamelCaseClass extends MyClass {} + + +// Incorrect usage of camel case. +trait invalidCamelCaseClass extends MyClass {} +trait Invalid_Camel_Case_Class_With_Underscores implements MyClass {} + + +// All lowercase. +trait invalidlowercaseclass extends MyClass {} +trait invalid_lowercase_class_with_underscores extends MyClass {} + + +// All uppercase. +trait VALIDUPPERCASECLASS extends MyClass {} +trait INVALID_UPPERCASE_CLASS_WITH_UNDERSCORES extends MyClass {} + + +// Mix camel case with uppercase. +trait ValidCamelCaseClassWithUPPERCASE extends MyClass {} + + +// Usage of numeric characters. +trait ValidCamelCaseClassWith1Number extends MyClass {} +trait ValidCamelCaseClassWith12345Numbers extends MyClass {} +trait 5InvalidCamelCaseClassStartingWithNumber extends MyClass {} +trait ValidCamelCaseClassEndingWithNumber5 extends MyClass {} +trait 12345 extends MyClass {} + +trait Testing{} + +trait Base +{ + protected $anonymous; + + public function __construct() + { + $this->anonymous = new class extends ArrayObject + { + public function __construct() + { + parent::__construct(['a' => 1, 'b' => 2]); + } + }; + } +} + +// Valid enum name. +enum ValidCamelCaseClass: string {} + + +// Incorrect usage of camel case. +enum invalidCamelCaseClass {} +enum Invalid_Camel_Case_Class_With_Underscores {} + + +// All lowercase. +enum invalidlowercaseclass: INT {} +enum invalid_lowercase_class_with_underscores {} + + +// All uppercase. +enum VALIDUPPERCASECLASS: int {} +enum INVALID_UPPERCASE_CLASS_WITH_UNDERSCORES {} + + +// Mix camel case with uppercase. +enum ValidCamelCaseClassWithUPPERCASE : string {} + + +// Usage of numeric characters. +enum ValidCamelCaseClassWith1Number {} +enum ValidCamelCaseClassWith12345Numbers : string {} +enum ValidCamelCaseClassEndingWithNumber5 {} + +enum Testing{} + +enum Base +{ + public function __construct() + { + $this->anonymous = new class extends ArrayObject + { + public function __construct() + { + parent::__construct(['a' => 1, 'b' => 2]); + } + }; + } +} + +if ( class_exists( Test :: class ) ) {} +if ( class_exists( Test2 ::class ) ) {} + +$foo = new class( + new class implements Countable { + } +) extends DateTime { +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.php new file mode 100644 index 0000000..e67ca84 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Classes/ValidClassNameUnitTest.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Classes; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidClassName sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ValidClassNameSniff + */ +class ValidClassNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 10 => 1, + 14 => 1, + 15 => 1, + 20 => 1, + 30 => 1, + 32 => 1, + 57 => 1, + 58 => 1, + 62 => 1, + 63 => 1, + 68 => 1, + 78 => 1, + 80 => 1, + 97 => 1, + 98 => 1, + 102 => 1, + 103 => 1, + 108 => 1, + 118 => 1, + 120 => 1, + 145 => 1, + 146 => 1, + 150 => 1, + 151 => 1, + 156 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/BlockCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/BlockCommentUnitTest.inc new file mode 100644 index 0000000..7cd04a2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/BlockCommentUnitTest.inc @@ -0,0 +1,309 @@ + + + + + + + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the BlockComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\BlockCommentSniff + */ +class BlockCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the test run. + * + * @return void + */ + public function setCliValues($testFile, $config) + { + $config->tabWidth = 4; + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + $errors = [ + 3 => 1, + 8 => 1, + 20 => 1, + 24 => 1, + 30 => 1, + 31 => 1, + 34 => 1, + 40 => 1, + 45 => 1, + 49 => 1, + 51 => 1, + 53 => 1, + 57 => 1, + 60 => 1, + 61 => 1, + 63 => 1, + 65 => 1, + 68 => 1, + 70 => 1, + 72 => 1, + 75 => 1, + 84 => 1, + 87 => 1, + 89 => 1, + 92 => 1, + 111 => 1, + 159 => 1, + 181 => 1, + 188 => 1, + 208 => 1, + 214 => 1, + 226 => 1, + 227 => 1, + 232 => 1, + 233 => 1, + 256 => 1, + 271 => 1, + 273 => 1, + ]; + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClassCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClassCommentUnitTest.inc new file mode 100644 index 0000000..8de3d0a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClassCommentUnitTest.inc @@ -0,0 +1,145 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClassComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\ClassCommentSniff + */ +class ClassCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 15 => 1, + 31 => 1, + 54 => 1, + 143 => 1, + 145 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 29 => 1, + 30 => 1, + 50 => 1, + 66 => 1, + 67 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClosingDeclarationCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClosingDeclarationCommentUnitTest.inc new file mode 100644 index 0000000..1a57149 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/ClosingDeclarationCommentUnitTest.inc @@ -0,0 +1,86 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClosingDeclarationComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\ClosingDeclarationCommentSniff + */ +class ClosingDeclarationCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 13 => 1, + 17 => 1, + 31 => 1, + 41 => 1, + 59 => 1, + 63 => 1, + 67 => 1, + 79 => 1, + 83 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [71 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc new file mode 100644 index 0000000..d95acd2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc @@ -0,0 +1,103 @@ + line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +class MyClass2 +{ + /** + * Some info about the variable here. + */ + var $x; +} + +abstract class MyClass +{ + /** +* Property comment + */ + readonly public string $prop; +} + +/** + * Some info about the enum here + * +*/ +enum Suits: string +{ + /** + * Some info about the case here. + */ + case HEARTS; +} + +/** ************************************************************************ + * Example with no errors. + **************************************************************************/ +function example() {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc.fixed new file mode 100644 index 0000000..ea6488a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.inc.fixed @@ -0,0 +1,103 @@ + line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +class MyClass2 +{ + /** + * Some info about the variable here. + */ + var $x; +} + +abstract class MyClass +{ + /** + * Property comment + */ + readonly public string $prop; +} + +/** + * Some info about the enum here + * + */ +enum Suits: string +{ + /** + * Some info about the case here. + */ + case HEARTS; +} + +/** ************************************************************************ + * Example with no errors. + **************************************************************************/ +function example() {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js new file mode 100644 index 0000000..6e1a878 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js @@ -0,0 +1,76 @@ + +/** +* Some info about the class here + * + */ +foo.prototype = { + + /** + * Some info about the function here. + * + *@return void + */ + bar: function() {} +} + +/** + * Some info about the class here + * + */ +foo.prototype = { + + /** + *Some info about the function here. + * + * @return void + */ + bar: function() {} +} + +/** + * Some info about the class here + * +*/ +foo.prototype = { + + /** + * Some info about the function here. + * + * @return void + */ + bar: function() {} +} + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +function myFunction() +{ + console.info('hi'); + /** + Comment here. + */ +} + +/** + * Creates a map of tokens => line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +$.extend(Datepicker.prototype, { + _widgetDatepicker: function() { + }, + /* Action for selecting a new month/year. */ +}); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js.fixed new file mode 100644 index 0000000..9edb4cc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.js.fixed @@ -0,0 +1,76 @@ + +/** + * Some info about the class here + * + */ +foo.prototype = { + + /** + * Some info about the function here. + * + * @return void + */ + bar: function() {} +} + +/** + * Some info about the class here + * + */ +foo.prototype = { + + /** + * Some info about the function here. + * + * @return void + */ + bar: function() {} +} + +/** + * Some info about the class here + * + */ +foo.prototype = { + + /** + * Some info about the function here. + * + * @return void + */ + bar: function() {} +} + +/** @var Database $mockedDatabase */ +/** @var Container $mockedContainer */ + +function myFunction() +{ + console.info('hi'); + /** + Comment here. + */ +} + +/** + * Creates a map of tokens => line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +$.extend(Datepicker.prototype, { + _widgetDatepicker: function() { + }, + /* Action for selecting a new month/year. */ +}); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.php new file mode 100644 index 0000000..6eab274 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/DocCommentAlignmentUnitTest.php @@ -0,0 +1,81 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DocCommentAlignment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\DocCommentAlignmentSniff + */ +class DocCommentAlignmentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + $errors = [ + 3 => 1, + 11 => 1, + 17 => 1, + 18 => 1, + 19 => 1, + 23 => 2, + 24 => 1, + 25 => 2, + 26 => 1, + 32 => 1, + 33 => 1, + 38 => 1, + 39 => 1, + ]; + + if ($testFile === 'DocCommentAlignmentUnitTest.inc') { + $errors[75] = 1; + $errors[83] = 1; + $errors[84] = 1; + $errors[90] = 1; + $errors[91] = 1; + $errors[95] = 1; + $errors[96] = 1; + } + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.inc new file mode 100644 index 0000000..cde6e46 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.inc @@ -0,0 +1,55 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.php new file mode 100644 index 0000000..6e795a2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/EmptyCatchCommentUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EmptyCatchComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\EmptyCatchCommentSniff + */ +class EmptyCatchCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 13 => 1, + 33 => 1, + 49 => 1, + 50 => 1, + 51 => 1, + 52 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc new file mode 100644 index 0000000..1db2861 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc @@ -0,0 +1,43 @@ + +* @author +* @copyright 1997~1994 The PHP Group +* @copyright 1994-1997 The PHP Group +* @copyright The PHP Group +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +?> + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc.fixed new file mode 100644 index 0000000..f584c55 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.inc.fixed @@ -0,0 +1,43 @@ + +* @author +* @copyright 1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 1994-1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 2024 Squiz Pty Ltd (ABN 77 084 670 600) +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +?> + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js new file mode 100644 index 0000000..57d8d37 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js @@ -0,0 +1,40 @@ + + + + +/** +* +* 0Multi-line short description without full stop +* +* +* asdasd +* long description for file (if any) +* asdasdadada +* +* PHP versio +* +* LICENSE: This source file is subject to version 3.0 of the PHP license +* that is available through the world-wide-web at the following URI: +* http://www.php.net/license/3_0.txt. If you did not receive a copy of +* the PHP License and are unable to obtain it through the web, please +* send a note to license@php.net so we can mail you a copy immediately. +* @package SquizCMS +* @package ADDITIONAL PACKAGE TAG +* @subpkg not_camelcased +* @author Antônio Carlos Venâncio Júnior +* @author +* @copyright 1997~1994 The PHP Group +* @copyright 1994-1997 The PHP Group +* @copyright The PHP Group +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +/** +* This bit here is not qualified as file comment +* +* as it is not the first comment in the file +* +*/ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js.fixed new file mode 100644 index 0000000..c7f54ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.1.js.fixed @@ -0,0 +1,40 @@ + + + + +/** +* +* 0Multi-line short description without full stop +* +* +* asdasd +* long description for file (if any) +* asdasdadada +* +* PHP versio +* +* LICENSE: This source file is subject to version 3.0 of the PHP license +* that is available through the world-wide-web at the following URI: +* http://www.php.net/license/3_0.txt. If you did not receive a copy of +* the PHP License and are unable to obtain it through the web, please +* send a note to license@php.net so we can mail you a copy immediately. +* @package SquizCMS +* @package ADDITIONAL PACKAGE TAG +* @subpkg not_camelcased +* @author Squiz Pty Ltd +* @author +* @copyright 1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 1994-1997 Squiz Pty Ltd (ABN 77 084 670 600) +* @copyright 2024 Squiz Pty Ltd (ABN 77 084 670 600) +* @license http://www.php.net/license/3_0.txt +* @summary An unknown summary tag +* +*/ + + +/** +* This bit here is not qualified as file comment +* +* as it is not the first comment in the file +* +*/ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.10.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.10.inc new file mode 100644 index 0000000..1f82abf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.10.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +readonly class Foo { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.inc new file mode 100644 index 0000000..520d349 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.inc @@ -0,0 +1,11 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +echo 'hi'; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.js new file mode 100644 index 0000000..4bb4d50 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.2.js @@ -0,0 +1,10 @@ +/** + * File comment. + * + * @package Package + * @subpackage Subpackage + * @author Squiz Pty Ltd + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +print 'hi'; \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.3.inc new file mode 100644 index 0000000..b47603f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.3.inc @@ -0,0 +1,9 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + * diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.4.inc new file mode 100644 index 0000000..2fdeeba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.4.inc @@ -0,0 +1,3 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +class Foo { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.7.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.7.inc new file mode 100644 index 0000000..7074dac --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.7.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ +#[Attribute] +class Foo { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.8.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.8.inc new file mode 100644 index 0000000..5ef90f2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.8.inc @@ -0,0 +1,9 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.9.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.9.inc new file mode 100644 index 0000000..f6c9d99 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.9.inc @@ -0,0 +1,12 @@ + + * @copyright 2010-2014 Squiz Pty Ltd (ABN 77 084 670 600) + */ + +enum Foo { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.php new file mode 100644 index 0000000..b7b686d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FileCommentUnitTest.php @@ -0,0 +1,82 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FileComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FileCommentSniff + */ +class FileCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FileCommentUnitTest.1.inc': + case 'FileCommentUnitTest.1.js': + return [ + 1 => 1, + 22 => 2, + 23 => 1, + 24 => 2, + 25 => 2, + 26 => 1, + 27 => 2, + 28 => 2, + 32 => 2, + ]; + + case 'FileCommentUnitTest.4.inc': + case 'FileCommentUnitTest.6.inc': + case 'FileCommentUnitTest.7.inc': + case 'FileCommentUnitTest.9.inc': + case 'FileCommentUnitTest.10.inc': + return [1 => 1]; + + case 'FileCommentUnitTest.5.inc': + return [2 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.inc new file mode 100644 index 0000000..7e94bb2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.inc @@ -0,0 +1,511 @@ +callSomeFunction(); + + }//end okFunction() + + + /** + * Comment inside function. + * + * @throws Exception + */ + function okFunction() + { + /** + * @var FooClass + */ + $foo = FooFactory::factory(); + throw new Exception; + + }//end okFunction + + /** + * Needs at throws tag for rethrown exception, + * even though we have one throws tag. + * + * @throws PHP_Exception1 + */ + public function notOkVariableRethrown() + { + throw new PHP_Exception1('Error'); + + try { + // Do something. + } catch (PHP_Exception2 $e) { + logError(); + throw $e; + } + + }//end notOkVariableRethrown() + + /** + * Needs at throws tag for rethrown exception, + * even though we have one throws tag. + * + * @throws PHP_Exception1 + */ + public function notOkVariableRethrown() + { + throw new PHP_Exception1('Error'); + + try { + // Do something. + } catch (PHP_Exception1 | PHP_Exception2 $e) { + logError(); + throw $e; + } + + }//end notOkVariableRethrown() + + /** + * Has correct throws tags for all exceptions + * + * @throws PHP_Exception1 + * @throws PHP_Exception2 + */ + public function okVariableRethrown() + { + throw new PHP_Exception1('Error'); + + try { + // Do something. + } catch (PHP_Exception2 $e) { + logError(); + throw $e; + } + + }//end okVariableRethrown() + + /** + * Has correct throws tags for all exceptions + * + * @throws PHP_Exception1 + * @throws PHP_Exception2 + */ + public function okVariableMultiRethrown() + { + try { + // Do something. + } catch (PHP_Exception1 | PHP_Exception2 $e) { + logError(); + throw $e; + } + + }//end okVariableMultiRethrown() +}//end class + +class NamespacedException { + /** + * @throws \Exception + */ + public function foo() { + throw new \Exception(); + } + + /** + * @throws \Foo\Bar\FooBarException + */ + public function fooBar2() { + throw new \Foo\Bar\FooBarException(); + } + + /** + * @throws FooBarException + */ + public function fooBar2() { + throw new \Foo\Bar\FooBarException(); + } +} + +class Foo { + /** + * Comment + */ + public function foo() { + }//end foo() + + public function bar() { + throw new Exception(); + } + + /** + * Returns information for a test. + * + * This info includes parameters, their valid values. + * + * @param integer $projectid Id of the project. + * + * @return array + * @throws ChannelException If the project is invalid. + */ + public static function getTestInfo($projectid=NULL) + { + try { + DAL::beginTransaction(); + DAL::commit(); + } catch (DALException $e) { + DAL::rollBack(); + throw new ChannelException($e); + } + } +} + +class Test +{ + /** + * Folder name. + * + * @var string + */ + protected $folderName; + + protected function setUp() + { + parent::setUp(); + + if ( !strlen($this->folderName) ) { + throw new \RuntimeException('The $this->folderName must be specified before proceeding.'); + } + } + + /* + * + */ + protected function foo() + { + } + + /** + * @return Closure + */ + public function getStuff() + { + return function () { + throw new RuntimeException("bam!"); + }; + } +} + +/** + * Class comment. + */ +class A +{ + /** + * Function B. + */ + public function b() + { + return new class { + public function c() + { + throw new \Exception(); + } + } + } +} + +/** + * Class comment. + */ +class A +{ + /** + * Function B. + */ + public function b() + { + return new class { + /** + * Tag and token number mismatch. + * + * @throws PHP_Exception1 + * @throws PHP_Exception2 + */ + public function oneLessThrowsTagNeeded() + { + throw new PHP_Exception1('Error'); + + }//end oneLessThrowsTagNeeded() + } + } +} + +abstract class SomeClass { + /** + * Comment here. + */ + abstract public function getGroups(); +} + +class SomeClass { + /** + * Validates something. + * + * @param string $method The set method parameter. + * + * @return string The validated method. + * + * @throws Prefix_Invalid_Argument_Exception The invalid argument exception. + * @throws InvalidArgumentException The invalid argument exception. + */ + protected function validate_something( $something ) { + if ( ! Prefix_Validator::is_string( $something ) ) { + throw Prefix_Invalid_Argument_Exception::invalid_string_parameter( $something, 'something' ); + } + + if ( ! in_array( $something, $this->valid_http_something, true ) ) { + throw new InvalidArgumentException( sprintf( '%s is not a valid HTTP something', $something ) ); + } + + return $something; + } + + /** + * Comment + * + * @throws Exception1 Comment. + * @throws Exception2 Comment. + * @throws Exception3 Comment. + */ + public function foo() { + switch ($foo) { + case 1: + throw Exception1::a(); + case 2: + throw Exception1::b(); + case 3: + throw Exception1::c(); + case 4: + throw Exception2::a(); + case 5: + throw Exception2::b(); + default: + throw new Exception3; + + } + } +} + +namespace Test\Admin { + class NameSpacedClass { + /** + * @throws \ExceptionFromGlobalNamespace + */ + public function ExceptionInGlobalNamespace() { + throw new \ExceptionFromGlobalNamespace(); + } + + /** + * @throws ExceptionFromSameNamespace + */ + public function ExceptionInSameNamespace() { + throw new ExceptionFromSameNamespace(); + } + + /** + * @throws \Test\Admin\ExceptionFromSameNamespace + */ + public function ExceptionInSameNamespaceToo() { + throw new ExceptionFromSameNamespace(); + } + + /** + * @throws \Different\NameSpaceName\ExceptionFromDifferentNamespace + */ + public function ExceptionInSameNamespaceToo() { + throw new \Different\NameSpaceName\ExceptionFromDifferentNamespace(); + } + } +} + +namespace { + class GlobalNameSpaceClass { + /** + * @throws SomeGlobalException + */ + public function ThrowGlobalException() { + throw new SomeGlobalException(); + } + + /** + * @throws \SomeGlobalException + */ + public function ThrowGlobalExceptionToo() { + throw new SomeGlobalException(); + } + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.php new file mode 100644 index 0000000..3854846 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentThrowTagUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionCommentThrowTag sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentThrowTagSniff + */ +class FunctionCommentThrowTagUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 9 => 1, + 21 => 1, + 35 => 1, + 47 => 1, + 61 => 2, + 106 => 1, + 123 => 1, + 200 => 1, + 219 => 1, + 287 => 1, + 397 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc new file mode 100644 index 0000000..a44f5e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc @@ -0,0 +1,1136 @@ +MyClass) + */ +public function caseSensitive($a1, $a2, $a3, arRay $a4, $a5, $a6, myclas $a7) +{ + +}//end caseSensitive() + + +/** + * More type hint check for custom type and array. + * + * @param array $a1 Comment here. + * @param array $a2 Comment here. + * @param MyClass $a3 Comment here. + * @param MyClass $a4 Comment here. + * + * @return array(int => MyClass) + */ +public function typeHint(MyClass $a1, $a2, myclass $a3, $a4) +{ + return (3 => 'myclass obj'); + +}//end typeHint() + + +/** + * Mixed variable type separated by a '|'. + * + * @param array|string $a1 Comment here. + * @param mixed $a2 Comment here. + * @param string|array $a3 Comment here. + * @param MyClass|int $a4 Comment here. + * + * @return bool + */ +public function mixedType($a1, $a2, $a3, $a4) +{ + return true; + +}//end mixedType() + + +/** + * Array type. + * + * @param array(MyClass) $a1 OK. + * @param array() $a2 Invalid type. + * @param array( $a3 Typo. + * @param array(int) $a4 Use 'array(integer)' instead. + * @param array(int => integer) $a5 Use 'array(integer => integer)' instead. + * @param array(integer => bool) $a6 Use 'array(integer => boolean)' instead. + * @param aRRay $a7 Use 'array' instead. + * @param string $a8 String with unknown type hint. + * + * @return int + */ +public function mixedArrayType($a1, $a2, array $a3, $a4, $a5, $a6, $a7, unknownTypeHint $a8) +{ + return 1; + +}//end mixedArrayType() + + +/** + */ +function empty1() +{ +}//end empty1() + + +/** + * + */ +function empty2() +{ +}//end empty2() + + +/** + * + * + * + */ +function empty3() +{ +}//end empty3 + + +/** + * @return boolean + */ +public function missingShortDescriptionInFunctionComment() +{ + return true; + +}//end missingShortDescriptionInFunctionComment() + + +class Another_Class +{ + + /** + * Destructor should not include a return tag. + * + * @return void + */ + function __destruct() + { + return; + } + + /** + * Constructor should not include a return tag. + * + * @return void + */ + function __construct() + { + return; + } + +}//end class + + +/** + * Comment param alignment test. + * + * @param string $varrr1 Comment1.. + * @param string $vr2 Comment2. + * @param string $var3 Comment3.. + * + * @return void + */ +public static function paramAlign($varrr1, $vr2, $var3) +{ + +}//end paramAlign() + + +/** + * Comment. + * + * @param string $id Comment. + * @param array $design Comment. + * + * @return void + */ +public static function paint($id, array $design) +{ + +}//end paint() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @since 4.0.0 + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + return; + } + + return 'blah'; + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + + return 'blah'; + +}//end myFunction() + +/** + * Test function. + * + * @param string $arg1 An argument + * + * @access public + * @return bool + */ + +echo $blah; + +function myFunction($arg1) {} + +class MyClass() { + /** + * An abstract function. + * + * @return string[] + */ + abstract final protected function myFunction(); +} + +/** + * Comment. + * + * @param mixed $test An argument. + * + * @return mixed + */ +function test($test) +{ + if ($test === TRUE) { + return; + } + + return $test; + +}//end test() + + +/** Comment. + * + * @return mixed + * + */ +function test() +{ + +}//end test() + +/** + * Comment. + * + * @param \other\ns\item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\ns\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +// Closures should be ignored. +preg_replace_callback( + '~-([a-z])~', + function ($match) { + return strtoupper($match[1]); + }, + 'hello-world' +); + +$callback = function ($bar) use ($foo) + { + $bar += $foo; + }; + +/** + * Comment should end with '*', not '**' before the slash. + **/ +function test123() { + +} + +/** + * Cant use resource for type hint. + * + * @param resource $test An argument. + * + * @return mixed + */ +function test($test) +{ + return $test; + +}//end test() + +/** + * Variable number of args. + * + * @param string $a1 Comment here. + * @param string $a2 Comment here. + * @param string $a2,... Comment here. + * + * @return boolean + */ +public function variableArgs($a1, $a2) +{ + return true; + +}//end variableArgs() + +/** + * Contains closure. + * + * @return void + */ +public function containsClosure() +{ + function ($e) { + return new Event($e); + }, + +}//end containsClosure() + +/** + * 这是一条测试评论. + * + * @return void + */ +public function test() +{ + +}//end variableArgs() + +/** + * Uses callable. + * + * @param callable $cb Test parameter. + * + * @return void + */ +public function usesCallable(callable $cb) { + $cb(); +}//end usesCallable() + +/** + * Creates a map of tokens => line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character + * to use for splitting strings. + * + * @return void + * @throws Exception If something really bad + * happens while doing foo. + */ +public function foo(array &$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Some description. + * + * @param \Vendor\Package\SomeClass $someclass Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass2 Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass3 Some class. + * + * @return void + */ +public function foo(SomeClass $someclass, \OtherVendor\Package\SomeClass2 $someclass2, SomeClass3 $someclass3) +{ +} + +/** + * Gettext. + * + * @return string + */ +public function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Test + * + * @return void + * @throws E + */ +function myFunction() {} + +/** + * Yield test + * + * @return integer + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Yield test + * + * @return void + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Using "array" as a type hint should satisfy a specified array parameter type. + * + * @param MyClass[] $values An array of MyClass objects. + * + * @return void + */ +public function specifiedArray(array $values) { + +}// end specifiedArray() + +/** + * Using "callable" as a type hint should satisfy a "callback" parameter type. + * + * @param callback $cb A callback. + * + * @return void + */ +public function callableCallback(callable $cb) { + +}// end callableCallback() + +/** + * PHP7 type hints. + * + * @param string $name1 Comment. + * @param integer $name2 Comment. + * @param float $name3 Comment. + * @param boolean $name4 Comment. + * + * @return void + */ +public function myFunction (string $name1, int $name2, float $name3, bool $name4) { +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + +/** + * Return description function + correct type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + incorrect type. + * + * @return int This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + no return. + * + * @return void This is a description. + */ +public function myFunction() { +} + +/** + * Return description function + mixed return. + * + * @return mixed This is a description. + */ +public function myFunction() { +} + +/** + * Function comment. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Do something. + * + * @return void + */ +public function someFunc(): void +{ + $class = new class + { + /** + * Do something. + * + * @return string + */ + public function getString(): string + { + return 'some string'; + } + }; +} + +/** + * Return description function + mixed return types. + * + * @return bool|int This is a description. + */ +function returnTypeWithDescriptionA() +{ + return 5; + +}//end returnTypeWithDescriptionA() + + +/** + * Return description function + mixed return types. + * + * @return real|bool This is a description. + */ +function returnTypeWithDescriptionB() +{ + return 5; + +}//end returnTypeWithDescriptionB() + + +/** + * Return description function + lots of different mixed return types. + * + * @return int|object|string[]|real|double|float|bool|array(int=>MyClass)|callable And here we have a description + */ +function returnTypeWithDescriptionC() +{ + return 5; + +}//end returnTypeWithDescriptionC() + + +/** + * Return description function + lots of different mixed return types. + * + * @return array(int=>bool)|\OtherVendor\Package\SomeClass2|MyClass[]|void And here we have a description + */ +function returnTypeWithDescriptionD() +{ + +}//end returnTypeWithDescriptionD() + +/** + * Yield from test + * + * @return int[] + */ +function yieldFromTest() +{ + yield from foo(); +} + +/** + * Audio + * + * Generates an audio element to embed sounds + * + * @param mixed $src Either a source string or + * an array of sources. + * @param mixed $unsupportedMessage The message to display + * if the media tag is not supported by the browser. + * @param mixed $attributes HTML attributes. + * @return string + */ +function audio( + $src, + $unsupportedMessage = '', + $attributes = '', +) +{ + return 'test'; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithClosure() +{ + function () { + return; + }; + + return []; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithAnonymousClass() +{ + new class { + /** + * @return void + */ + public function test() { + return; + } + }; + + return []; +} + +/** + * @return void + */ +function returnVoidWithClosure() +{ + function () { + return 1; + }; +} + +/** + * @return void + */ +function returnVoidWithAnonymousClass() +{ + new class { + /** + * @return integer + */ + public function test() + { + return 1; + } + }; +} + +class TestReturnVoid +{ + /** + * @return void + */ + public function test() + { + function () { + return 4; + }; + } +} + +/** + * Comment here. + * + * @param integer $a This is A. + * @param ?array $b This is B. + * + * @return void + */ +public static function foo(?int $a, ?array $b) {} + +/** + * Comment here. + * + * @param object $a This is A. + * @param object $b This is B. + * + * @return void + */ +public function foo(object $a, ?object $b) {} + +/** + * Prepares given PHP class method for later code building. + * + * @param integer $foo Comment. + * - Additional comment. + * + * @return void + */ +function foo($foo) {} + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +// phpcs:set Squiz.Commenting.FunctionComment skipIfInheritdoc true + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +/** + * Foo. + * + * @param mixed $a Comment. + * + * @return mixed + */ +public function foo(mixed $a): mixed {} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] __construct,__destruct + +/** + * @return void + * @throws Exception If any other error occurs. */ +function throwCommentOneLine() {} + +/** + * When two adjacent pipe symbols are used (by mistake), the sniff should not throw a PHP Fatal error + * + * @param stdClass||null $object While invalid, this should not throw a PHP Fatal error. + * @return void + */ +function doublePipeFatalError(?stdClass $object) {} + +/** + * Test for passing variables by reference + * + * This sniff treats the '&' as optional for parameters passed by reference, but + * forbidden for parameters which are not passed by reference. + * + * Because mismatches may be in either direction, we cannot auto-fix these. + * + * @param string $foo A string passed in by reference. + * @param string &$bar A string passed in by reference. + * @param string $baz A string NOT passed in by reference. + * @param string &$qux A string NOT passed in by reference. + * @param string &$case1 A string passed in by reference with a case mismatch. + * @param string &$CASE2 A string NOT passed in by reference, also with a case mismatch. + * + * @return void + */ +public function variablesPassedByReference(&$foo, &$bar, $baz, $qux, &$CASE1, $case2) +{ + return; +} + +/** + * Test for param tag containing ref, but param in declaration not being by ref. + * + * @param string &$foo This should be flagged as (only) ParamNameUnexpectedAmpersandPrefix. + * @param string &$bar This should be flagged as (only) ParamNameNoMatch. + * @param string &$baz This should be flagged as (only) ParamNameNoCaseMatch. + * + * @return void + */ +function passedByRefMismatch($foo, $bra, $BAZ) { + return; +} + +/** + * Test variable case + * + * @param string $foo This parameter is lowercase. + * @param string $BAR This parameter is UPPERCASE. + * @param string $BazQux This parameter is TitleCase. + * @param string $corgeGrault This parameter is camelCase. + * @param string $GARPLY This parameter should be in lowercase. + * @param string $waldo This parameter should be in TitleCase. + * @param string $freD This parameter should be in UPPERCASE. + * @param string $PLUGH This parameter should be in TitleCase. + * + * @return void + */ +public function variableCaseTest( + $foo, + $BAR, + $BazQux, + $corgeGrault, + $garply, + $Waldo, + $FRED, + $PluGh +) { + return; +} + +/** + * Test variable order mismatch + * + * @param string $foo This is the third parameter. + * @param string $bar This is the first parameter. + * @param string $baz This is the second parameter. + * + * @return void + */ +public function variableOrderMismatch($bar, $baz, $foo) { + return; +} + +/** + * @return never + */ +function foo() {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc.fixed new file mode 100644 index 0000000..3d2e10f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.inc.fixed @@ -0,0 +1,1136 @@ + MyClass) + */ +public function caseSensitive($a1, $a2, $a3, arRay $a4, $a5, $a6, myclas $a7) +{ + +}//end caseSensitive() + + +/** + * More type hint check for custom type and array. + * + * @param array $a1 Comment here. + * @param array $a2 Comment here. + * @param MyClass $a3 Comment here. + * @param MyClass $a4 Comment here. + * + * @return array(integer => MyClass) + */ +public function typeHint(MyClass $a1, $a2, myclass $a3, $a4) +{ + return (3 => 'myclass obj'); + +}//end typeHint() + + +/** + * Mixed variable type separated by a '|'. + * + * @param array|string $a1 Comment here. + * @param mixed $a2 Comment here. + * @param string|array $a3 Comment here. + * @param MyClass|integer $a4 Comment here. + * + * @return boolean + */ +public function mixedType($a1, $a2, $a3, $a4) +{ + return true; + +}//end mixedType() + + +/** + * Array type. + * + * @param array(MyClass) $a1 OK. + * @param array $a2 Invalid type. + * @param array $a3 Typo. + * @param array(integer) $a4 Use 'array(integer)' instead. + * @param array(integer => integer) $a5 Use 'array(integer => integer)' instead. + * @param array(integer => boolean) $a6 Use 'array(integer => boolean)' instead. + * @param array $a7 Use 'array' instead. + * @param string $a8 String with unknown type hint. + * + * @return integer + */ +public function mixedArrayType($a1, $a2, array $a3, $a4, $a5, $a6, $a7, unknownTypeHint $a8) +{ + return 1; + +}//end mixedArrayType() + + +/** + */ +function empty1() +{ +}//end empty1() + + +/** + * + */ +function empty2() +{ +}//end empty2() + + +/** + * + * + * + */ +function empty3() +{ +}//end empty3 + + +/** + * @return boolean + */ +public function missingShortDescriptionInFunctionComment() +{ + return true; + +}//end missingShortDescriptionInFunctionComment() + + +class Another_Class +{ + + /** + * Destructor should not include a return tag. + * + * @return void + */ + function __destruct() + { + return; + } + + /** + * Constructor should not include a return tag. + * + * @return void + */ + function __construct() + { + return; + } + +}//end class + + +/** + * Comment param alignment test. + * + * @param string $varrr1 Comment1.. + * @param string $vr2 Comment2. + * @param string $var3 Comment3.. + * + * @return void + */ +public static function paramAlign($varrr1, $vr2, $var3) +{ + +}//end paramAlign() + + +/** + * Comment. + * + * @param string $id Comment. + * @param array $design Comment. + * + * @return void + */ +public static function paint($id, array $design) +{ + +}//end paint() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @since 4.0.0 + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + return; + } + + return 'blah'; + +}//end myFunction() + + +/** + * Adds specified class name to class attribute of this widget. + * + * @return string + */ +public function myFunction() +{ + if ($condition === FALSE) { + echo 'hi'; + } + + return 'blah'; + +}//end myFunction() + +/** + * Test function. + * + * @param string $arg1 An argument + * + * @access public + * @return bool + */ + +echo $blah; + +function myFunction($arg1) {} + +class MyClass() { + /** + * An abstract function. + * + * @return string[] + */ + abstract final protected function myFunction(); +} + +/** + * Comment. + * + * @param mixed $test An argument. + * + * @return mixed + */ +function test($test) +{ + if ($test === TRUE) { + return; + } + + return $test; + +}//end test() + + +/** Comment. + * + * @return mixed + * + */ +function test() +{ + +}//end test() + +/** + * Comment. + * + * @param \other\ns\item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param item $test An argument. + * + * @return mixed + */ +function test(\other\ns\item $test) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\ns\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +/** + * Comment. + * + * @param \first\item $test An argument. + * + * @return mixed + */ +function test(\first\ns\item $test = \second\ns::CONSTANT) +{ + return $test; + +}//end test() + +// Closures should be ignored. +preg_replace_callback( + '~-([a-z])~', + function ($match) { + return strtoupper($match[1]); + }, + 'hello-world' +); + +$callback = function ($bar) use ($foo) + { + $bar += $foo; + }; + +/** + * Comment should end with '*', not '**' before the slash. + **/ +function test123() { + +} + +/** + * Cant use resource for type hint. + * + * @param resource $test An argument. + * + * @return mixed + */ +function test($test) +{ + return $test; + +}//end test() + +/** + * Variable number of args. + * + * @param string $a1 Comment here. + * @param string $a2 Comment here. + * @param string $a2,... Comment here. + * + * @return boolean + */ +public function variableArgs($a1, $a2) +{ + return true; + +}//end variableArgs() + +/** + * Contains closure. + * + * @return void + */ +public function containsClosure() +{ + function ($e) { + return new Event($e); + }, + +}//end containsClosure() + +/** + * 这是一条测试评论. + * + * @return void + */ +public function test() +{ + +}//end variableArgs() + +/** + * Uses callable. + * + * @param callable $cb Test parameter. + * + * @return void + */ +public function usesCallable(callable $cb) { + $cb(); +}//end usesCallable() + +/** + * Creates a map of tokens => line numbers for each token. + * + * @param array $tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to process this file. + * @param string $eolChar The EOL character + * to use for splitting strings. + * + * @return void + * @throws Exception If something really bad + * happens while doing foo. + */ +public function foo(array &$tokens, $tokenizer, $eolChar) +{ + +}//end foo() + +/** + * Some description. + * + * @param \Vendor\Package\SomeClass $someclass Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass2 Some class. + * @param \OtherVendor\Package\SomeClass2 $someclass3 Some class. + * + * @return void + */ +public function foo(SomeClass $someclass, \OtherVendor\Package\SomeClass2 $someclass2, SomeClass3 $someclass3) +{ +} + +/** + * Gettext. + * + * @return string + */ +public function _() { + return $foo; +} + +class Baz { + /** + * The PHP5 constructor + * + * No return tag + */ + public function __construct() { + + } +} + +/** + * Test + * + * @return void + * @throws E + */ +function myFunction() {} + +/** + * Yield test + * + * @return integer + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Yield test + * + * @return void + */ +function yieldTest() +{ + for ($i = 0; $i < 5; $i++) { + yield $i; + } +} + +/** + * Using "array" as a type hint should satisfy a specified array parameter type. + * + * @param MyClass[] $values An array of MyClass objects. + * + * @return void + */ +public function specifiedArray(array $values) { + +}// end specifiedArray() + +/** + * Using "callable" as a type hint should satisfy a "callback" parameter type. + * + * @param callback $cb A callback. + * + * @return void + */ +public function callableCallback(callable $cb) { + +}// end callableCallback() + +/** + * PHP7 type hints. + * + * @param string $name1 Comment. + * @param integer $name2 Comment. + * @param float $name3 Comment. + * @param boolean $name4 Comment. + * + * @return void + */ +public function myFunction (string $name1, int $name2, float $name3, bool $name4) { +} + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string ...$name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + + +/** + * Variadic function. + * + * @param string $name1 Comment. + * @param string $name2 Comment. + * + * @return void + */ +public function myFunction(string $name1, string ...$name2) { +} + +/** + * Return description function + correct type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + incorrect type. + * + * @return integer This is a description. + */ +public function myFunction() { + return 5; +} + +/** + * Return description function + no return. + * + * @return void This is a description. + */ +public function myFunction() { +} + +/** + * Return description function + mixed return. + * + * @return mixed This is a description. + */ +public function myFunction() { +} + +/** + * Function comment. + * + * @param $bar + * Comment here. + * @param ... + * Additional arguments here. + * + * @return + * Return value + * + */ +function foo($bar) { +} + +/** + * Do something. + * + * @return void + */ +public function someFunc(): void +{ + $class = new class + { + /** + * Do something. + * + * @return string + */ + public function getString(): string + { + return 'some string'; + } + }; +} + +/** + * Return description function + mixed return types. + * + * @return boolean|integer This is a description. + */ +function returnTypeWithDescriptionA() +{ + return 5; + +}//end returnTypeWithDescriptionA() + + +/** + * Return description function + mixed return types. + * + * @return float|boolean This is a description. + */ +function returnTypeWithDescriptionB() +{ + return 5; + +}//end returnTypeWithDescriptionB() + + +/** + * Return description function + lots of different mixed return types. + * + * @return integer|object|string[]|float|boolean|array(integer => MyClass)|callable And here we have a description + */ +function returnTypeWithDescriptionC() +{ + return 5; + +}//end returnTypeWithDescriptionC() + + +/** + * Return description function + lots of different mixed return types. + * + * @return array(integer => boolean)|\OtherVendor\Package\SomeClass2|MyClass[]|void And here we have a description + */ +function returnTypeWithDescriptionD() +{ + +}//end returnTypeWithDescriptionD() + +/** + * Yield from test + * + * @return int[] + */ +function yieldFromTest() +{ + yield from foo(); +} + +/** + * Audio + * + * Generates an audio element to embed sounds + * + * @param mixed $src Either a source string or + * an array of sources. + * @param mixed $unsupportedMessage The message to display + * if the media tag is not supported by the browser. + * @param mixed $attributes HTML attributes. + * @return string + */ +function audio( + $src, + $unsupportedMessage = '', + $attributes = '', +) +{ + return 'test'; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithClosure() +{ + function () { + return; + }; + + return []; +} + +/** + * Test function + * + * @return array + */ +function returnArrayWithAnonymousClass() +{ + new class { + /** + * @return void + */ + public function test() { + return; + } + }; + + return []; +} + +/** + * @return void + */ +function returnVoidWithClosure() +{ + function () { + return 1; + }; +} + +/** + * @return void + */ +function returnVoidWithAnonymousClass() +{ + new class { + /** + * @return integer + */ + public function test() + { + return 1; + } + }; +} + +class TestReturnVoid +{ + /** + * @return void + */ + public function test() + { + function () { + return 4; + }; + } +} + +/** + * Comment here. + * + * @param integer $a This is A. + * @param array $b This is B. + * + * @return void + */ +public static function foo(?int $a, ?array $b) {} + +/** + * Comment here. + * + * @param object $a This is A. + * @param object $b This is B. + * + * @return void + */ +public function foo(object $a, ?object $b) {} + +/** + * Prepares given PHP class method for later code building. + * + * @param integer $foo Comment. + * - Additional comment. + * + * @return void + */ +function foo($foo) {} + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +// phpcs:set Squiz.Commenting.FunctionComment skipIfInheritdoc true + +/** + * {@inheritDoc} + */ +public function foo($a, $b) {} + +/** + * Foo. + * + * @param mixed $a Comment. + * + * @return mixed + */ +public function foo(mixed $a): mixed {} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] +class Bar { + /** + * The PHP5 constructor + */ + public function __construct() { + + } +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] ignored +/** + * Should be ok + */ +public function ignored() { + +} + +// phpcs:set Squiz.Commenting.FunctionComment specialMethods[] __construct,__destruct + +/** + * @return void + * @throws Exception If any other error occurs. */ +function throwCommentOneLine() {} + +/** + * When two adjacent pipe symbols are used (by mistake), the sniff should not throw a PHP Fatal error + * + * @param stdClass|null $object While invalid, this should not throw a PHP Fatal error. + * @return void + */ +function doublePipeFatalError(?stdClass $object) {} + +/** + * Test for passing variables by reference + * + * This sniff treats the '&' as optional for parameters passed by reference, but + * forbidden for parameters which are not passed by reference. + * + * Because mismatches may be in either direction, we cannot auto-fix these. + * + * @param string $foo A string passed in by reference. + * @param string &$bar A string passed in by reference. + * @param string $baz A string NOT passed in by reference. + * @param string &$qux A string NOT passed in by reference. + * @param string &$case1 A string passed in by reference with a case mismatch. + * @param string &$CASE2 A string NOT passed in by reference, also with a case mismatch. + * + * @return void + */ +public function variablesPassedByReference(&$foo, &$bar, $baz, $qux, &$CASE1, $case2) +{ + return; +} + +/** + * Test for param tag containing ref, but param in declaration not being by ref. + * + * @param string &$foo This should be flagged as (only) ParamNameUnexpectedAmpersandPrefix. + * @param string &$bar This should be flagged as (only) ParamNameNoMatch. + * @param string &$baz This should be flagged as (only) ParamNameNoCaseMatch. + * + * @return void + */ +function passedByRefMismatch($foo, $bra, $BAZ) { + return; +} + +/** + * Test variable case + * + * @param string $foo This parameter is lowercase. + * @param string $BAR This parameter is UPPERCASE. + * @param string $BazQux This parameter is TitleCase. + * @param string $corgeGrault This parameter is camelCase. + * @param string $GARPLY This parameter should be in lowercase. + * @param string $waldo This parameter should be in TitleCase. + * @param string $freD This parameter should be in UPPERCASE. + * @param string $PLUGH This parameter should be in TitleCase. + * + * @return void + */ +public function variableCaseTest( + $foo, + $BAR, + $BazQux, + $corgeGrault, + $garply, + $Waldo, + $FRED, + $PluGh +) { + return; +} + +/** + * Test variable order mismatch + * + * @param string $foo This is the third parameter. + * @param string $bar This is the first parameter. + * @param string $baz This is the second parameter. + * + * @return void + */ +public function variableOrderMismatch($bar, $baz, $foo) { + return; +} + +/** + * @return never + */ +function foo() {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.php new file mode 100644 index 0000000..6433dbe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/FunctionCommentUnitTest.php @@ -0,0 +1,202 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff + */ +class FunctionCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + $errors = [ + 5 => 1, + 10 => 3, + 12 => 2, + 13 => 2, + 14 => 1, + 15 => 1, + 28 => 1, + 43 => 1, + 76 => 1, + 87 => 1, + 103 => 1, + 109 => 1, + 112 => 1, + 122 => 1, + 123 => 3, + 124 => 2, + 125 => 1, + 126 => 1, + 137 => 4, + 138 => 4, + 139 => 4, + 143 => 2, + 155 => 1, + 159 => 1, + 166 => 1, + 173 => 1, + 183 => 1, + 190 => 2, + 193 => 2, + 196 => 1, + 199 => 2, + 210 => 1, + 211 => 1, + 222 => 1, + 223 => 1, + 224 => 1, + 225 => 1, + 226 => 1, + 227 => 1, + 230 => 2, + 232 => 2, + 246 => 1, + 248 => 4, + 261 => 1, + 263 => 1, + 276 => 1, + 277 => 1, + 278 => 1, + 279 => 1, + 280 => 1, + 281 => 1, + 284 => 1, + 286 => 7, + 294 => 1, + 302 => 1, + 312 => 1, + 358 => 1, + 359 => 2, + 372 => 1, + 373 => 1, + 387 => 1, + 407 => 1, + 441 => 1, + 500 => 1, + 526 => 1, + 548 => 1, + 641 => 1, + 669 => 1, + 688 => 1, + 744 => 1, + 748 => 1, + 767 => 1, + 789 => 1, + 792 => 1, + 794 => 1, + 797 => 1, + 801 => 1, + 828 => 1, + 840 => 1, + 852 => 1, + 864 => 1, + 886 => 1, + 888 => 1, + 890 => 1, + 978 => 1, + 997 => 1, + 1004 => 2, + 1006 => 1, + 1029 => 1, + 1053 => 1, + 1058 => 2, + 1069 => 1, + 1070 => 1, + 1071 => 1, + 1080 => 2, + 1083 => 1, + 1084 => 1, + 1085 => 1, + 1093 => 4, + 1100 => 1, + 1101 => 1, + 1102 => 1, + 1103 => 1, + 1123 => 1, + 1124 => 1, + 1125 => 1, + ]; + + // Scalar type hints only work from PHP 7 onwards. + if (PHP_VERSION_ID >= 70000) { + $errors[17] = 3; + $errors[128] = 1; + $errors[143] = 3; + $errors[161] = 2; + $errors[201] = 1; + $errors[232] = 7; + $errors[363] = 3; + $errors[377] = 1; + $errors[575] = 2; + $errors[627] = 1; + $errors[1002] = 1; + $errors[1075] = 6; + $errors[1089] = 3; + $errors[1107] = 8; + $errors[1129] = 3; + } else { + $errors[729] = 4; + $errors[740] = 2; + $errors[752] = 2; + $errors[982] = 1; + }//end if + + // Object type hints only work from PHP 7.2 onwards. + if (PHP_VERSION_ID >= 70200) { + $errors[627] = 2; + } else { + $errors[992] = 2; + } + + // Mixed type hints only work from PHP 8.0 onwards. + if (PHP_VERSION_ID >= 80000) { + $errors[265] = 1; + $errors[459] = 1; + $errors[893] = 3; + } else { + $errors[1023] = 1; + } + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc new file mode 100644 index 0000000..0248768 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc @@ -0,0 +1,196 @@ + One +// -> One.One +// -> Two + +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + +/** + * Comment should be ignored in PHP 5.4. + * + */ +trait MyTrait { + +} + +$foo = 'foo'; // Var set to foo. + +echo $foo; + +// Comment here. +echo $foo; + +/** + * Comments about the include + */ +include_once($blah); + +// some comment without capital or full stop +echo $foo; // An unrelated comment. + +// An unrelated comment. +echo $foo; // some comment without capital or full stop + +class Foo +{ + // This is fine. + + /** + * Spacing is ignored above. + */ + function bar(){} +} + +if ($foo) { +}//end if +// Another comment here. +$foo++; + +if ($foo) { +}//end if +// another comment here. +$foo++; + +/** + * Comment should be ignored, even though there is an attribute between the docblock and the class declaration. + */ + +#[AttributeA] + +final class MyClass +{ + /** + * Comment should be ignored, even though there is an attribute between the docblock and the function declaration + */ + #[AttributeA] + #[AttributeB] + final public function test() {} +} + +/** + * Comment should be ignored. + * + */ +enum MyEnum { + +} + +/** + * Comment should be ignored. + * + */ +readonly class MyClass +{ + /** + * Comment should be ignored. + * + */ + readonly $property = 10; +} + +/* + * N.B.: The below test line must be the last test in the file. + * Testing that a new line after an inline comment when it's the last non-whitespace + * token in a file, does *not* throw an error as this would conflict with the common + * "new line required at end of file" rule. + */ + +// For this test line having an empty line below it, is fine. diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc.fixed new file mode 100644 index 0000000..949a9ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.inc.fixed @@ -0,0 +1,189 @@ + One +// -> One.One +// -> Two +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + +/** + * Comment should be ignored in PHP 5.4. + * + */ +trait MyTrait { + +} + +$foo = 'foo'; // Var set to foo. + +echo $foo; + +// Comment here. +echo $foo; + +/** + * Comments about the include + */ +include_once($blah); + +// some comment without capital or full stop +echo $foo; // An unrelated comment. + +// An unrelated comment. +echo $foo; // some comment without capital or full stop + +class Foo +{ + // This is fine. + + /** + * Spacing is ignored above. + */ + function bar(){} +} + +if ($foo) { +}//end if +// Another comment here. +$foo++; + +if ($foo) { +}//end if +// another comment here. +$foo++; + +/** + * Comment should be ignored, even though there is an attribute between the docblock and the class declaration. + */ + +#[AttributeA] + +final class MyClass +{ + /** + * Comment should be ignored, even though there is an attribute between the docblock and the function declaration + */ + #[AttributeA] + #[AttributeB] + final public function test() {} +} + +/** + * Comment should be ignored. + * + */ +enum MyEnum { + +} + +/** + * Comment should be ignored. + * + */ +readonly class MyClass +{ + /** + * Comment should be ignored. + * + */ + readonly $property = 10; +} + +/* + * N.B.: The below test line must be the last test in the file. + * Testing that a new line after an inline comment when it's the last non-whitespace + * token in a file, does *not* throw an error as this would conflict with the common + * "new line required at end of file" rule. + */ + +// For this test line having an empty line below it, is fine. diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js new file mode 100644 index 0000000..6b1093e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js @@ -0,0 +1,129 @@ +// Some content here. +var code = 'hello'; + +// This comment contains # multiple +// hash signs (#). +code = 'hello'; + +/** + * This is the first line of a function comment. + * This is the second line. + */ +function testFunction() +{ + // Callback methods which are added by external objects. + this.callbacks = {}; + +}//end testFunction() + +/** + * This is the first line of a class comment. + * This is the second line. + */ +myClass.prototype = { + + /** + * This is the first line of a method comment. + * This is the second line. + */ + load: function(url, callback) + { + // Some code here. + + } +}; + +// some code goes here! + +/* + A longer comment goes here. + It spans multiple lines!! + Or does it? +*/ + +// 0This is a simple multi-line +// comment! +code = 'hello'; + +//This is not valid. +code = 'hello'; + +// Neither is this! +code = 'hello'; + +// +code = 'hello'; + +/** Neither is this! **/ +code = 'hello'; + +/** + * This is the first line of a function comment. + * This is the second line. + */ +var myFunction = function() { +} + +/** + * This is the first line of a function comment. + * This is the second line. + */ +myFunction = function() { +} + +/** + * This is the first line of a function comment. + * This is the second line. + */ +myClass.myFunction = function() { +} + +dfx.getIframeDocument = function(iframe) +{ + return doc; + +};//end dfx.getIframeDocument() + +mig.Gallery.prototype = { + + init: function(cb) + { + + },//end init() + + imageClicked: function(id) + { + + }//end imageClicked() + +}; + +// Here is some inline example code: +// -> One +// -> One.One +// -> Two + +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + + +var foo = 'foo'; // Var set to foo. + +console.info(foo); + +// Comment here. +console.info(foo); + +//** +* invalid comment +*/ + +// some comment without capital or full stop +console.log(foo); // An unrelated comment. + +// An unrelated comment. +console.log(foo); // some comment without capital or full stop diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js.fixed new file mode 100644 index 0000000..20e5041 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.js.fixed @@ -0,0 +1,125 @@ +// Some content here. +var code = 'hello'; + +// This comment contains # multiple +// hash signs (#). +code = 'hello'; + +/** + * This is the first line of a function comment. + * This is the second line. + */ +function testFunction() +{ + // Callback methods which are added by external objects. + this.callbacks = {}; + +}//end testFunction() + +/** + * This is the first line of a class comment. + * This is the second line. + */ +myClass.prototype = { + + /** + * This is the first line of a method comment. + * This is the second line. + */ + load: function(url, callback) + { + // Some code here. + } +}; + +// some code goes here! +/* + A longer comment goes here. + It spans multiple lines!! + Or does it? +*/ + +// 0This is a simple multi-line +// comment! +code = 'hello'; + +// This is not valid. +code = 'hello'; + +// Neither is this! +code = 'hello'; + +code = 'hello'; + +/** Neither is this! **/ +code = 'hello'; + +/** + * This is the first line of a function comment. + * This is the second line. + */ +var myFunction = function() { +} + +/** + * This is the first line of a function comment. + * This is the second line. + */ +myFunction = function() { +} + +/** + * This is the first line of a function comment. + * This is the second line. + */ +myClass.myFunction = function() { +} + +dfx.getIframeDocument = function(iframe) +{ + return doc; + +};//end dfx.getIframeDocument() + +mig.Gallery.prototype = { + + init: function(cb) + { + + },//end init() + + imageClicked: function(id) + { + + }//end imageClicked() + +}; + +// Here is some inline example code: +// -> One +// -> One.One +// -> Two +/* + Here is some inline example code: + -> One + -> One.One + -> Two +*/ + + +var foo = 'foo'; // Var set to foo. + +console.info(foo); + +// Comment here. +console.info(foo); + +// ** +* invalid comment +*/ + +// some comment without capital or full stop +console.log(foo); // An unrelated comment. + +// An unrelated comment. +console.log(foo); // some comment without capital or full stop diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.php new file mode 100644 index 0000000..dbaccb2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/InlineCommentUnitTest.php @@ -0,0 +1,96 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the InlineComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\InlineCommentSniff + */ +class InlineCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'InlineCommentUnitTest.inc': + $errors = [ + 17 => 1, + 27 => 1, + 28 => 1, + 32 => 2, + 36 => 1, + 44 => 2, + 58 => 1, + 61 => 1, + 64 => 1, + 67 => 1, + 95 => 1, + 96 => 1, + 97 => 3, + 118 => 1, + 126 => 2, + 130 => 2, + 149 => 1, + ]; + + return $errors; + case 'InlineCommentUnitTest.js': + return [ + 31 => 1, + 36 => 2, + 48 => 1, + 51 => 1, + 54 => 1, + 57 => 1, + 102 => 1, + 103 => 1, + 104 => 3, + 118 => 1, + 121 => 1, + 125 => 2, + 129 => 2, + ]; + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc new file mode 100644 index 0000000..d6c4cf6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc @@ -0,0 +1,1033 @@ + match ($foo) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 + }, +]; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc.fixed new file mode 100644 index 0000000..176cfe2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.inc.fixed @@ -0,0 +1,1033 @@ + match ($foo) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 + },//end match +]; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js new file mode 100644 index 0000000..c0cf282 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js @@ -0,0 +1,444 @@ +function long_function() +{ + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + }//end if + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + } + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + } else { + // Short ELSE + }//end if + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + } else { + // Short ELSE + } +} + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end for + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + for (val =1; val < 20; val++) { + // Short for. + } + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end while + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + while (something) { + // Short while. + } + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} + +if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } +} //end if + +if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } +} else { + // Short ELSE +} //end if + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} //end for + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} //end while + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end for + +if (true) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} else if (condition) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} else { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end if + +if (something) { + // Line 1 + // Line 2 +} else if (somethingElse) { + // Line 1 + // Line 2 +} else { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} + +switch (something) { + case '1': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '2': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '3': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '4': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '5': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; +} + +// Wrong comment +if (condition) { + condition = true; +}//end foreach diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js.fixed new file mode 100644 index 0000000..231b51c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.js.fixed @@ -0,0 +1,444 @@ +function long_function() +{ + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + }//end if + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + }//end if + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + } else { + // Short ELSE + }//end if + + if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } + } else { + // Short ELSE + }//end if +} + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end for + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + for (val =1; val < 20; val++) { + // Short for. + } + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end for + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end while + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + while (something) { + // Short while. + } + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end while + +if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } +} //end if + +if (longFunction) { + // This is a long + // IF statement + // that does + // not have + // an ELSE + // block on it + variable = 'hello'; + + if (variable === 'hello') { + // This is a short + // IF statement + } + + if (variable === 'hello') { + // This is a short + // IF statement + } else { + // This is a short ELSE + // statement + } +} else { + // Short ELSE +} //end if + +for (variable=1; variable < 20; variable++) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} //end for + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} //end while + +while (variable < 20) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end while + +if (true) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} else if (condition) { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +} else { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end if + +if (something) { + // Line 1 + // Line 2 +} else if (somethingElse) { + // Line 1 + // Line 2 +} else { + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + // Line 6 + // Line 7 + // Line 8 + // Line 9 + // Line 10 + // Line 11 + // Line 12 + // Line 13 + // Line 14 + // Line 15 + // Line 16 + // Line 17 + // Line 18 + // Line 19 + // Line 20 +}//end if + +switch (something) { + case '1': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '2': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '3': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '4': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; + case '5': + // Line 1 + // Line 2 + // Line 3 + // Line 4 + // Line 5 + break; +}//end switch + +// Wrong comment +if (condition) { + condition = true; +}//end if diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.php new file mode 100644 index 0000000..a24a68a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/LongConditionClosingCommentUnitTest.php @@ -0,0 +1,107 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LongConditionClosingComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\LongConditionClosingCommentSniff + */ +class LongConditionClosingCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'LongConditionClosingCommentUnitTest.inc': + return [ + 49 => 1, + 99 => 1, + 146 => 1, + 192 => 1, + 215 => 1, + 238 => 1, + 261 => 1, + 286 => 1, + 309 => 1, + 332 => 1, + 355 => 1, + 378 => 1, + 493 => 1, + 531 => 1, + 536 => 1, + 540 => 1, + 562 => 1, + 601 => 1, + 629 => 1, + 663 => 1, + 765 => 1, + 798 => 1, + 811 => 1, + 897 => 1, + 931 => 1, + 962 => 1, + 985 => 2, + 1008 => 1, + 1032 => 1, + ]; + + case 'LongConditionClosingCommentUnitTest.js': + return [ + 47 => 1, + 97 => 1, + 144 => 1, + 190 => 1, + 213 => 1, + 238 => 1, + 261 => 1, + 284 => 1, + 307 => 1, + 401 => 1, + 439 => 1, + 444 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js new file mode 100644 index 0000000..6de6421 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js @@ -0,0 +1,36 @@ +function test(id, buttons) // cool function +{ + alert('hello'); + alert('hello again'); // And again. + // Valid comment. + +}//end test() + +var good = true; // Indeed. + +mig.Gallery.prototype = { + + init: function(cb) + { + + },//end init() + + imageClicked: function(id) + { + + }//end imageClicked() + +}; + +dfx.getIframeDocument = function(iframe) +{ + + return doc; + +};//end dfx.getIframeDocument() + +// Verify that multi-line control structure with comments and annotations are left alone. +if (condition // comment + && anotherCondition) { + condition = true; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js.fixed new file mode 100644 index 0000000..1953760 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.1.js.fixed @@ -0,0 +1,39 @@ +function test(id, buttons) +// cool function +{ + alert('hello'); + alert('hello again'); +// And again. + // Valid comment. + +}//end test() + +var good = true; +// Indeed. + +mig.Gallery.prototype = { + + init: function(cb) + { + + },//end init() + + imageClicked: function(id) + { + + }//end imageClicked() + +}; + +dfx.getIframeDocument = function(iframe) +{ + + return doc; + +};//end dfx.getIframeDocument() + +// Verify that multi-line control structure with comments and annotations are left alone. +if (condition // comment + && anotherCondition) { + condition = true; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.2.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.2.js new file mode 100644 index 0000000..88d0e7d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.2.js @@ -0,0 +1,2 @@ +// Comment as first thing in a JS file. +var i = 100; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc new file mode 100644 index 0000000..b834696 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc @@ -0,0 +1,54 @@ + function($b) { + }, // comment. + 'key' => 'value', // phpcs:ignore Standard.Category.SniffName -- for reasons. + 'key' => 'value', // comment. +]; + +// Verify that multi-line control structure with comments and annotations are left alone. +for ( + $i = 0; /* Start */ + $i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + $i++ // comment + +) {} + +if ( $condition === true // comment + && $anotherCondition === false +) {} + +$match = match($foo // comment + && $bar +) { + 1 => 1, // comment +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc.fixed new file mode 100644 index 0000000..21a4bbe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.inc.fixed @@ -0,0 +1,59 @@ + function($b) { + }, // comment. + 'key' => 'value', // phpcs:ignore Standard.Category.SniffName -- for reasons. + 'key' => 'value', +// comment. +]; + +// Verify that multi-line control structure with comments and annotations are left alone. +for ( + $i = 0; /* Start */ + $i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + $i++ // comment + +) {} + +if ( $condition === true // comment + && $anotherCondition === false +) {} + +$match = match($foo // comment + && $bar +) { + 1 => 1, +// comment +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.php new file mode 100644 index 0000000..7d7f270 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/PostStatementCommentUnitTest.php @@ -0,0 +1,74 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the PostStatementComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\PostStatementCommentSniff + */ +class PostStatementCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'PostStatementCommentUnitTest.inc': + return [ + 6 => 1, + 10 => 1, + 18 => 1, + 35 => 1, + 53 => 1, + ]; + + case 'PostStatementCommentUnitTest.1.js': + return [ + 1 => 1, + 4 => 1, + 9 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc new file mode 100644 index 0000000..54ef5d2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc @@ -0,0 +1,456 @@ + $content) { + echo $content; + } + + return $var1; + + }//end checkVariable() + + + /** + * + * + */ + $emptyVarDoc = ''; + + /** + * Var type checking (int v.s. integer). + * + * @var int + */ + private $_varSimpleTypeCheck; + + + /** + * Var type checking (array(int => string) v.s. array(int => string)). + * + * @var array(int => string) + */ + private $_varArrayTypeCheck; + + + /** + * Boolean @var tag Capitalized + * + * @var Boolean + */ + public $CapBoolTag = true; + + + /** + * Boolean @var tag Capitalized + * + * @var BOOLEAN + */ + public $CapBoolTag2 = true; + + + /** + * Double @var tag Capitalized + * + * @var Double + */ + public $CapDoubleTag = 1; + + + /** + * Double @var tag Capitalized + * + * @var DOUBLE + */ + public $CapDoubleTag2 = 1; + + + /** + * Real @var tag Capitalized + * + * @var Real + */ + public $CapRealTag = 1; + + + /** + * Real @var tag Capitalized + * + * @var REAL + */ + public $CapRealTag2 = 1; + + + /** + * Float @var tag Capitalized + * + * @var Float + */ + public $CapFloatTag = 1; + + + /** + * Float @var tag Capitalized + * + * @var FLOAT + */ + public $CapFloatTag2 = 1; + + + /** + * Int @var tag Capitalized + * + * @var Int + */ + public $CapIntTag = 1; + + + /** + * Int @var tag Capitalized + * + * @var INT + */ + public $CapIntTag2 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var Integer + */ + public $CapIntTag3 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var INTEGER + */ + public $CapIntTag4 = 1; + + + /** + * Array @var tag Capitalized + * + * @var Array + */ + public $CapVarTag = []; + + + /** + * Array @var tag All Caps + * + * @var ARRAY + */ + public $CapVarTag2 = []; + + + /** + * Array @var tag Capitalized + * + * @var Array() + */ + public $CapVarTag3 = []; + + + /** + * Array @var tag All Caps + * + * @var ARRAY() + */ + public $CapVarTag4 = []; + + + /** + * Var type checking (STRING v.s. string). + * + * @var STRING + */ + private $_varCaseTypeCheck; + + + /** + * @var integer + */ + private $_varWithNoShortComment; + + protected $noComment2 = ''; + + + /** + * @var int Var type checking (int v.s. integer) with single-line comment. + */ + private $_varSimpleTypeCheckSingleLine; + + +}//end class + + +/** + * VariableCommentUnitTest2. + * + * Long description goes here. + * + */ +class VariableCommentUnitTest2 +{ + + public $hello; + + /** Comment starts here. + * + * @var string + * + */ + private $_varCaseTypeCheck; + + /** + * 这是一条测试评论. + * + * @var string + */ + public $foo; + +}//end class + + +/* + * Class comment + */ +class Foo +{ + + protected $bar; + + /** + * Short description of the member variable. + * + * @var array + */ + public static array $variableName = array(); + +} + +class Foo +{ + + /** + * Short description of the member variable. + * + * @var array + */ + public array $variableName = array(); + + + // Not "/**" style comment. + // + // @var string + private ?Folder\ClassName $_incorrectCommentStyle = null; + + + var int $noComment = 1; + } + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; +} + +class ReadOnlyProps +{ + /** + * Short description of the member variable. + * + * @var array + */ + public readonly array $variableName = array(); + + /** + * Short description of the member variable. + * + * @var + */ + readonly protected ?int $variableName = 10; + + private readonly string $variable; +} + +class UnionTypes +{ + /** + * @var array|boolean + */ + private array|bool $variableName = array(); +} + +class IntersectionTypes +{ + /** + * @var \Iterator|\Countable + */ + private \Iterator&\Countable $variableName; +} + +class StandaloneNullTrueFalseTypes +{ + /** + * @var null + */ + public null $variableName = null; + + /** + * @var true + */ + protected true $variableName = true; + + /** + * @var false + */ + private false $variableName = false; +} + +class MoreMissingButSupportedTypes +{ + /** + * @var parent + */ + public parent $variableName; + + /** + * @var self + */ + protected self $variableName; + + /** + * @var SomeClass + */ + private namespace\SomeClass $variableName; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc.fixed new file mode 100644 index 0000000..a292b6d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.inc.fixed @@ -0,0 +1,456 @@ + $content) { + echo $content; + } + + return $var1; + + }//end checkVariable() + + + /** + * + * + */ + $emptyVarDoc = ''; + + /** + * Var type checking (int v.s. integer). + * + * @var integer + */ + private $_varSimpleTypeCheck; + + + /** + * Var type checking (array(int => string) v.s. array(int => string)). + * + * @var array(integer => string) + */ + private $_varArrayTypeCheck; + + + /** + * Boolean @var tag Capitalized + * + * @var boolean + */ + public $CapBoolTag = true; + + + /** + * Boolean @var tag Capitalized + * + * @var boolean + */ + public $CapBoolTag2 = true; + + + /** + * Double @var tag Capitalized + * + * @var float + */ + public $CapDoubleTag = 1; + + + /** + * Double @var tag Capitalized + * + * @var float + */ + public $CapDoubleTag2 = 1; + + + /** + * Real @var tag Capitalized + * + * @var float + */ + public $CapRealTag = 1; + + + /** + * Real @var tag Capitalized + * + * @var float + */ + public $CapRealTag2 = 1; + + + /** + * Float @var tag Capitalized + * + * @var float + */ + public $CapFloatTag = 1; + + + /** + * Float @var tag Capitalized + * + * @var float + */ + public $CapFloatTag2 = 1; + + + /** + * Int @var tag Capitalized + * + * @var integer + */ + public $CapIntTag = 1; + + + /** + * Int @var tag Capitalized + * + * @var integer + */ + public $CapIntTag2 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var integer + */ + public $CapIntTag3 = 1; + + + /** + * Integer @var tag Capitalized + * + * @var integer + */ + public $CapIntTag4 = 1; + + + /** + * Array @var tag Capitalized + * + * @var array + */ + public $CapVarTag = []; + + + /** + * Array @var tag All Caps + * + * @var array + */ + public $CapVarTag2 = []; + + + /** + * Array @var tag Capitalized + * + * @var array + */ + public $CapVarTag3 = []; + + + /** + * Array @var tag All Caps + * + * @var array + */ + public $CapVarTag4 = []; + + + /** + * Var type checking (STRING v.s. string). + * + * @var string + */ + private $_varCaseTypeCheck; + + + /** + * @var integer + */ + private $_varWithNoShortComment; + + protected $noComment2 = ''; + + + /** + * @var integer Var type checking (int v.s. integer) with single-line comment. + */ + private $_varSimpleTypeCheckSingleLine; + + +}//end class + + +/** + * VariableCommentUnitTest2. + * + * Long description goes here. + * + */ +class VariableCommentUnitTest2 +{ + + public $hello; + + /** Comment starts here. + * + * @var string + * + */ + private $_varCaseTypeCheck; + + /** + * 这是一条测试评论. + * + * @var string + */ + public $foo; + +}//end class + + +/* + * Class comment + */ +class Foo +{ + + protected $bar; + + /** + * Short description of the member variable. + * + * @var array + */ + public static array $variableName = array(); + +} + +class Foo +{ + + /** + * Short description of the member variable. + * + * @var array + */ + public array $variableName = array(); + + + // Not "/**" style comment. + // + // @var string + private ?Folder\ClassName $_incorrectCommentStyle = null; + + + var int $noComment = 1; + } + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; +} + +class ReadOnlyProps +{ + /** + * Short description of the member variable. + * + * @var array + */ + public readonly array $variableName = array(); + + /** + * Short description of the member variable. + * + * @var + */ + readonly protected ?int $variableName = 10; + + private readonly string $variable; +} + +class UnionTypes +{ + /** + * @var array|boolean + */ + private array|bool $variableName = array(); +} + +class IntersectionTypes +{ + /** + * @var \Iterator|\Countable + */ + private \Iterator&\Countable $variableName; +} + +class StandaloneNullTrueFalseTypes +{ + /** + * @var null + */ + public null $variableName = null; + + /** + * @var true + */ + protected true $variableName = true; + + /** + * @var false + */ + private false $variableName = false; +} + +class MoreMissingButSupportedTypes +{ + /** + * @var parent + */ + public parent $variableName; + + /** + * @var self + */ + protected self $variableName; + + /** + * @var SomeClass + */ + private namespace\SomeClass $variableName; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.php new file mode 100644 index 0000000..0cb3e19 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Commenting/VariableCommentUnitTest.php @@ -0,0 +1,88 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Commenting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the VariableComment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\VariableCommentSniff + */ +class VariableCommentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 21 => 1, + 24 => 1, + 56 => 1, + 64 => 1, + 73 => 1, + 84 => 1, + 130 => 1, + 136 => 1, + 144 => 1, + 152 => 1, + 160 => 1, + 168 => 1, + 176 => 1, + 184 => 1, + 192 => 1, + 200 => 1, + 208 => 1, + 216 => 1, + 224 => 1, + 232 => 1, + 240 => 1, + 248 => 1, + 256 => 1, + 264 => 1, + 272 => 1, + 280 => 1, + 290 => 1, + 294 => 1, + 311 => 1, + 336 => 1, + 361 => 1, + 364 => 1, + 399 => 1, + 403 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [93 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc new file mode 100644 index 0000000..6496f7f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc @@ -0,0 +1,324 @@ + 0); + +do +{ + echo $i; +} while ($i > 0); + +do +{ + echo $i; +} +while ($i > 0); + +do { echo $i; } while ($i > 0); + +do{ + echo $i; +}while($i > 0); + +while ($i < 1) { + echo $i; +} + +while($i < 1){ + echo $i; +} + +while ($i < 1) { echo $i; } + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for($i = 1; $i < 1; $i++){ + echo $i; +} + +for ($i = 1; $i < 1; $i++) { echo $i; } + +if ($i == 0) { + $i = 1; +} + +if($i == 0){ + $i = 1; +} + +if ($i == 0) { $i = 1; } + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else{ + $i = 0; +} + +if ($i == 0) { $i = 1; } else { $i = 0; } + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +}else if($i == 2){ + $i = 0; +} + +if ($i == 0) { $i = 1; } else if ($i == 2) { $i = 0; } + +if ($i == 0) { // comments are allowed + $i = 1; +} + +if ($i == 0) {// comments are allowed + $i = 1; +} + +if ($i == 0) { /* comments are allowed*/ + $i = 1; +} + +if ($i == 0) +{ // this is ok + $i = 1; +} + +if ($i == 0) /* this is ok */ { +} + +try { + $code = 'this'; +} catch (Exception $e) { + // Caught! +} + +try { $code = 'this'; } catch (Exception $e) { + // Caught! +} + +do { echo $i; +} while ($i > 0); + +if ($i === 0) { + + $i = 1 +} + +if ($a) { + +} +elseif ($b) { +} + +foreach ($items as $item) { + echo $item; +} + +foreach($items as $item){ + echo $item; +} + +if ($a && $b) // && $c) +{ +} + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +try { + // try body +} +catch (FirstExceptionType $e) { + // catch body +} +catch (OtherExceptionType $e) { + // catch body +} + +switch($foo) { + + case 'bar': + break; + +} + +if ($foo) : +endif; + +?> + +getRow()): ?> +

    + + + +
    + +
    + + + + + + + hello + + + + hello + + + + +getRow()) : ?> +

    + + + + + + + + hello + + + + hello + + 1, +}; + +$r = match($x){1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5): + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 + +// Intentional parse error. This should be the last test in the file. +foreach + // Some unrelated comment. diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc.fixed new file mode 100644 index 0000000..c8834a3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.inc.fixed @@ -0,0 +1,328 @@ + 0); + +do { + echo $i; +} while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +do { +echo $i; } while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { +echo $i; } + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { +echo $i; } + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { +$i = 1; } + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else { +$i = 0; } + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else if ($i == 2) { +$i = 0; } + +if ($i == 0) { // comments are allowed + $i = 1; +} + +if ($i == 0) {// comments are allowed + $i = 1; +} + +if ($i == 0) { /* comments are allowed*/ + $i = 1; +} + +if ($i == 0) { // this is ok + $i = 1; +} + +if ($i == 0) { /* this is ok */ +} + +try { + $code = 'this'; +} catch (Exception $e) { + // Caught! +} + +try { +$code = 'this'; } catch (Exception $e) { + // Caught! +} + +do { +echo $i; +} while ($i > 0); + +if ($i === 0) { + + $i = 1 +} + +if ($a) { + +} elseif ($b) { +} + +foreach ($items as $item) { + echo $item; +} + +foreach ($items as $item) { + echo $item; +} + +if ($a && $b) { // && $c) +} + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +try { + // try body +} catch (FirstExceptionType $e) { + // catch body +} catch (OtherExceptionType $e) { + // catch body +} + +switch ($foo) { + + case 'bar': + break; + +} + +if ($foo) : +endif; + +?> + +getRow()) : ?> +

    + + + +
    + +
    + + + + + + + hello + + + + hello + + + + +getRow()): ?> +

    + + + + + + + + hello + + + + hello + + 1, +}; + +$r = match ($x) { +1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 + +// Intentional parse error. This should be the last test in the file. +foreach + // Some unrelated comment. diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js new file mode 100644 index 0000000..6c2e9ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js @@ -0,0 +1,135 @@ + +i = 0; +do { + i = 0; +} while (i > 0); + +do +{ + i = 0; +} while (i > 0); + +do +{ + i = 0; +} +while (i > 0); + +do { i = 0; } while (i > 0); + +do{ + i = 0; +}while(i > 0); + +while (i < 1) { + i = 0; +} + +while(i < 1){ + i = 0; +} + +while (i < 1) { i = 0; } + +for (i = 1; i < 1; i++) { + i = 0; +} + +for(i = 1; i < 1; i++){ + i = 0; +} + +for (i = 1; i < 1; i++) { i = 0; } + +if (i == 0) { + i = 1; +} + +if(i == 0){ + i = 1; +} + +if (i == 0) { i = 1; } + +if (i == 0) { + i = 1; +} else { + i = 0; +} + +if (i == 0) { + i = 1; +}else{ + i = 0; +} + +if (i == 0) { i = 1; } else { i = 0; } + +if (i == 0) { + i = 1; +} else if (i == 2) { + i = 0; +} + +if (i == 0) { + i = 1; +}else if(i == 2){ + i = 0; +} + +if (i == 0) { i = 1; } else if (i == 2) { i = 0; } + +if (i == 0) { // comments are allowed + i = 1; +} + +if (i == 0) {// comments are allowed + i = 1; +} + +if (i == 0) { /* comments are allowed*/ + i = 1; +} + +if (i == 0) +{ // this is ok + i = 1; +} + +if (i == 0) /* this is ok */ { +} + +try { + code = 'this'; +} catch (e) { + // Caught! +} + +try { code = 'this'; } catch (e) { + // Caught! +} + +do { i = 0; +} while (i > 0); + +if (i === 0) { + + i = 1 +} + +if (window.jQuery)(function($) { + $.fn.reset = function() { + return this.each(function() { + try { + this.reset(); + } catch (e) { + } + }); + }; +})(jQuery); + +if ($("#myid").rotationDegrees()=='90') + $('.modal').css({'transform': 'rotate(90deg)'}); + +if ($("#myid").rotationDegrees()=='90') + $foo = {'transform': 'rotate(90deg)'}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js.fixed new file mode 100644 index 0000000..e3ed6de --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.js.fixed @@ -0,0 +1,141 @@ + +i = 0; +do { + i = 0; +} while (i > 0); + +do { + i = 0; +} while (i > 0); + +do { + i = 0; +} while (i > 0); + +do { +i = 0; } while (i > 0); + +do { + i = 0; +} while (i > 0); + +while (i < 1) { + i = 0; +} + +while (i < 1) { + i = 0; +} + +while (i < 1) { +i = 0; } + +for (i = 1; i < 1; i++) { + i = 0; +} + +for (i = 1; i < 1; i++) { + i = 0; +} + +for (i = 1; i < 1; i++) { +i = 0; } + +if (i == 0) { + i = 1; +} + +if (i == 0) { + i = 1; +} + +if (i == 0) { +i = 1; } + +if (i == 0) { + i = 1; +} else { + i = 0; +} + +if (i == 0) { + i = 1; +} else { + i = 0; +} + +if (i == 0) { +i = 1; } else { +i = 0; } + +if (i == 0) { + i = 1; +} else if (i == 2) { + i = 0; +} + +if (i == 0) { + i = 1; +} else if (i == 2) { + i = 0; +} + +if (i == 0) { +i = 1; } else if (i == 2) { +i = 0; } + +if (i == 0) { // comments are allowed + i = 1; +} + +if (i == 0) {// comments are allowed + i = 1; +} + +if (i == 0) { /* comments are allowed*/ + i = 1; +} + +if (i == 0) { // this is ok + i = 1; +} + +if (i == 0) { /* this is ok */ +} + +try { + code = 'this'; +} catch (e) { + // Caught! +} + +try { +code = 'this'; } catch (e) { + // Caught! +} + +do { +i = 0; +} while (i > 0); + +if (i === 0) { + + i = 1 +} + +if (window.jQuery)(function($) { + $.fn.reset = function() { + return this.each(function() { + try { + this.reset(); + } catch (e) { + } + }); + }; +})(jQuery); + +if ($("#myid").rotationDegrees()=='90') + $('.modal').css({'transform': 'rotate(90deg)'}); + +if ($("#myid").rotationDegrees()=='90') + $foo = {'transform': 'rotate(90deg)'}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.php new file mode 100644 index 0000000..3187047 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ControlSignatureUnitTest.php @@ -0,0 +1,109 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ControlSignature sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff + */ +class ControlSignatureUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + $errors = [ + 7 => 1, + 12 => 1, + 15 => 1, + 18 => 1, + 20 => 1, + 22 => 2, + 28 => 2, + 32 => 1, + 38 => 2, + 42 => 1, + 48 => 2, + 52 => 1, + 62 => 2, + 66 => 2, + 76 => 4, + 80 => 2, + 94 => 1, + 99 => 1, + 108 => 1, + 112 => 1, + ]; + + if ($testFile === 'ControlSignatureUnitTest.inc') { + $errors[122] = 1; + $errors[130] = 2; + $errors[134] = 1; + $errors[150] = 1; + $errors[153] = 1; + $errors[158] = 1; + $errors[165] = 1; + $errors[170] = 2; + $errors[185] = 1; + $errors[190] = 2; + $errors[191] = 2; + $errors[195] = 1; + $errors[227] = 1; + $errors[234] = 1; + $errors[239] = 2; + $errors[243] = 2; + $errors[244] = 2; + $errors[248] = 1; + $errors[259] = 1; + $errors[262] = 1; + $errors[267] = 1; + $errors[269] = 1; + $errors[276] = 1; + $errors[279] = 1; + $errors[283] = 1; + $errors[306] = 3; + $errors[309] = 1; + $errors[315] = 1; + }//end if + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc new file mode 100644 index 0000000..91d0a23 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ElseIfDeclarationUnitTest.inc @@ -0,0 +1,14 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ElseIfDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ElseIfDeclarationSniff + */ +class ElseIfDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 8 => 1, + 13 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc new file mode 100644 index 0000000..4709923 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc @@ -0,0 +1,36 @@ + $that) { +} + +// Invalid. +foreach ( $something as $blah => $that ) { +} + +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach (${something}AS$blah=>$that) { +} + +// The works. +foreach ( $something aS $blah => $that ) { +} + +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 1 +foreach ($something as $blah => $that) {} +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 0 + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..b0de6eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.inc.fixed @@ -0,0 +1,36 @@ + $that) { +} + +// Invalid. +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach ($something as $blah => $that) { +} + +foreach (${something} as $blah => $that) { +} + +// The works. +foreach ($something as $blah => $that) { +} + +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 1 +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +foreach ( $something as $blah => $that ) {} +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForEachLoopDeclaration requiredSpacesBeforeClose 0 + +foreach ([ + 'foo' => 'bar', + 'foobaz' => 'bazzy', + ] as $key => $value) { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.php new file mode 100644 index 0000000..da7f144 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForEachLoopDeclarationUnitTest.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ForEachLoopDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForEachLoopDeclarationSniff + */ +class ForEachLoopDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 8 => 2, + 11 => 2, + 14 => 2, + 17 => 5, + 21 => 7, + 26 => 2, + 28 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc new file mode 100644 index 0000000..5022e74 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc @@ -0,0 +1,129 @@ +i ; }; $i < function() { return $this->max; }; $i++) {} +for ($i = function() { return $this->i; }; $i < function() { return $this->max; } ; $i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines true +for ( + $i = 0; + $i < 5; + $i++ +) { + // body here +} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines false + +// This test has to be the last one in the file! Intentional parse error check. +for diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..6a1e763 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.inc.fixed @@ -0,0 +1,95 @@ +i ; }; $i < function() { return $this->max; }; $i++) {} +for ($i = function() { return $this->i; }; $i < function() { return $this->max; }; $i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines true +for ( + $i = 0; + $i < 5; + $i++ +) { + // body here +} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration ignoreNewlines false + +// This test has to be the last one in the file! Intentional parse error check. +for diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js new file mode 100644 index 0000000..cfda6c1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js @@ -0,0 +1,125 @@ +// Valid. +for (var i = 0; i < 10; i++) { +} + +// Invalid. +for ( i = 0; i < 10; i++ ) { +} + +for (i = 0; i < 10; i++) { +} + +for (var i = 0 ; i < 10 ; i++) { +} + +for (i = 0;i < 10;i++) { +} + +// The works. +for ( var i = 0 ; i < 10 ; i++ ) { +} + +this.formats = {}; +dfx.inherits('ContentFormat', 'Widget'); + +for (var widgetid in this.loadedContents) { + if (dfx.isset(widget) === true) { + widget.loadAutoSaveCWidgetStore.setData('activeScreen', null);widget.getContents(this.loadedContents[widgetid], function() {self.widgetLoaded(widget.id);}); + } +} + +for (var i = 0; i < 10;) { +} +for (var i = 0; i < 10; ) { +} + +for (var i = 0; ; i++) { +} +for (var i = 0;; i++) { +} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for (var i = 0; i < 10; i++) {} +for ( var i = 0; i < 10; i++ ) {} +for ( var i = 0; i < 10; i++ ) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +for ( ; i < 10; i++) {} +for (; i < 10; i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for ( ; i < 10; i++ ) {} +for ( ; i < 10; i++ ) {} +for (; i < 10; i++ ) {} + +for ( i = 0; i < 10; ) {} +for ( i = 0; i < 10;) {} +for ( i = 0; i < 10; ) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +// Test handling of comments and inline annotations. +for ( /*phpcs:enable*/ i = 0 /*start*/ ; /*end*/i < 10/*comment*/; i++ /*comment*/ ) {} + +// Test multi-line FOR control structure. +for ( + i = 0; + i < 10; + i++ +) {} + +// Test multi-line FOR control structure with comments and annotations. +for ( + i = 0; /* Start */ + i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + i++ // comment + +) {} + +// Test fixing each error in one go. Note: lines 84 + 88 contain trailing whitespace on purpose. +for ( + + + i = 0 + + ; + + i < 10 + + ; + + i++ + + +) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for ( + + + + i = 0 + + ; + + i < 10 + + ; + + i++ + + +) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +// Test with semi-colon not belonging to for. +for (i = function() {self.widgetLoaded(widget.id) ; }; i < function() {self.widgetLoaded(widget.id);}; i++) {} +for (i = function() {self.widgetLoaded(widget.id);}; i < function() {self.widgetLoaded(widget.id);} ; i++) {} + +// This test has to be the last one in the file! Intentional parse error check. +for diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js.fixed new file mode 100644 index 0000000..00ced64 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.js.fixed @@ -0,0 +1,91 @@ +// Valid. +for (var i = 0; i < 10; i++) { +} + +// Invalid. +for (i = 0; i < 10; i++) { +} + +for (i = 0; i < 10; i++) { +} + +for (var i = 0; i < 10; i++) { +} + +for (i = 0; i < 10; i++) { +} + +// The works. +for (var i = 0; i < 10; i++) { +} + +this.formats = {}; +dfx.inherits('ContentFormat', 'Widget'); + +for (var widgetid in this.loadedContents) { + if (dfx.isset(widget) === true) { + widget.loadAutoSaveCWidgetStore.setData('activeScreen', null);widget.getContents(this.loadedContents[widgetid], function() {self.widgetLoaded(widget.id);}); + } +} + +for (var i = 0; i < 10;) { +} +for (var i = 0; i < 10;) { +} + +for (var i = 0;; i++) { +} +for (var i = 0;; i++) { +} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for ( var i = 0; i < 10; i++ ) {} +for ( var i = 0; i < 10; i++ ) {} +for ( var i = 0; i < 10; i++ ) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +for (; i < 10; i++) {} +for (; i < 10; i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for ( ; i < 10; i++ ) {} +for ( ; i < 10; i++ ) {} +for ( ; i < 10; i++ ) {} + +for ( i = 0; i < 10; ) {} +for ( i = 0; i < 10; ) {} +for ( i = 0; i < 10; ) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +// Test handling of comments and inline annotations. +for (/*phpcs:enable*/ i = 0 /*start*/; /*end*/i < 10/*comment*/; i++ /*comment*/) {} + +// Test multi-line FOR control structure. +for (i = 0; i < 10; i++) {} + +// Test multi-line FOR control structure with comments and annotations. +for (i = 0; /* Start */ + i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + i++ // comment + +) {} + +// Test fixing each error in one go. Note: lines 84 + 88 contain trailing whitespace on purpose. +for (i = 0; i < 10; i++) {} + +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 1 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 1 +for ( i = 0; i < 10; i++ ) {} +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesAfterOpen 0 +// phpcs:set Squiz.ControlStructures.ForLoopDeclaration requiredSpacesBeforeClose 0 + +// Test with semi-colon not belonging to for. +for (i = function() {self.widgetLoaded(widget.id) ; }; i < function() {self.widgetLoaded(widget.id);}; i++) {} +for (i = function() {self.widgetLoaded(widget.id);}; i < function() {self.widgetLoaded(widget.id);}; i++) {} + +// This test has to be the last one in the file! Intentional parse error check. +for diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.php new file mode 100644 index 0000000..5ceba29 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.php @@ -0,0 +1,137 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ForLoopDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForLoopDeclarationSniff + */ +class ForLoopDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ForLoopDeclarationUnitTest.inc': + return [ + 8 => 2, + 11 => 2, + 14 => 2, + 17 => 2, + 21 => 6, + 27 => 1, + 30 => 1, + 37 => 2, + 39 => 2, + 43 => 1, + 49 => 1, + 50 => 1, + 53 => 1, + 54 => 1, + 59 => 4, + 62 => 1, + 63 => 1, + 64 => 1, + 66 => 1, + 69 => 1, + 74 => 1, + 77 => 1, + 82 => 2, + 86 => 2, + 91 => 1, + 95 => 1, + 101 => 2, + 105 => 2, + 110 => 1, + 116 => 2, + ]; + + case 'ForLoopDeclarationUnitTest.js': + return [ + 6 => 2, + 9 => 2, + 12 => 2, + 15 => 2, + 19 => 6, + 33 => 1, + 36 => 1, + 43 => 2, + 45 => 2, + 49 => 1, + 55 => 1, + 56 => 1, + 59 => 1, + 60 => 1, + 65 => 4, + 68 => 1, + 69 => 1, + 70 => 1, + 72 => 1, + 75 => 1, + 80 => 1, + 83 => 1, + 88 => 2, + 92 => 2, + 97 => 1, + 101 => 1, + 107 => 2, + 111 => 2, + 116 => 1, + 122 => 2, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'ForLoopDeclarationUnitTest.inc': + return [129 => 1]; + + case 'ForLoopDeclarationUnitTest.js': + return [125 => 1]; + + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc new file mode 100644 index 0000000..f54ed8a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc @@ -0,0 +1,48 @@ +id.'"', + '"'.$this->stepInfo['title'].'"', + '"'.((isset($this->stepInfo['description']) === TRUE) ? $this->stepInfo['description'] : '').'"', + '"'.(isset($this->stepInfo['description']) === TRUE ? $this->stepInfo['description'] : '').'"', + '"'.$this->stepInfo['title'].'"', + ); + +echo (TRUE)?'Hello':'Bye'; + +$array = array( + 'one' => ($test == 1) ? true : false, + 'two' => (($test == 1) ? true : false), + 'three' => (($test == 1) ? true : false) +); +$var = ($test == 1) ? true : false; +$var = (myFunc(1,2,3) == 1) ? true : false; + +set('config', function() { + $foo = ($bar === "on") ? "1" : "2"; +}); + +$config = function() { + $foo = ($bar === "on") ? "1" : "2"; +}; + +rand(0, 1) ? 'ěščřžýáí' : NULL; + +$c = ($argv[1]) ? : ""; +$filepath = realpath($argv[1]) ?: $argv[1]; +$c = ($argv[1]) ? /* comment */ : ""; +$c = ($argv[1]) ? +: ""; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed new file mode 100644 index 0000000..f7aa1d6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.inc.fixed @@ -0,0 +1,48 @@ +id.'"', + '"'.$this->stepInfo['title'].'"', + '"'.((isset($this->stepInfo['description']) === TRUE) ? $this->stepInfo['description'] : '').'"', + '"'.(isset($this->stepInfo['description']) === TRUE ? $this->stepInfo['description'] : '').'"', + '"'.$this->stepInfo['title'].'"', + ); + +echo (TRUE) ? 'Hello' : 'Bye'; + +$array = array( + 'one' => ($test == 1) ? true : false, + 'two' => (($test == 1) ? true : false), + 'three' => (($test == 1) ? true : false) +); +$var = ($test == 1) ? true : false; +$var = (myFunc(1,2,3) == 1) ? true : false; + +set('config', function() { + $foo = ($bar === "on") ? "1" : "2"; +}); + +$config = function() { + $foo = ($bar === "on") ? "1" : "2"; +}; + +rand(0, 1) ? 'ěščřžýáí' : NULL; + +$c = ($argv[1]) ?: ""; +$filepath = realpath($argv[1]) ?: $argv[1]; +$c = ($argv[1]) ? /* comment */ : ""; +$c = ($argv[1]) ? +: ""; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.php new file mode 100644 index 0000000..0fa7b26 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/InlineIfDeclarationUnitTest.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the InlineIfDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\InlineIfDeclarationSniff + */ +class InlineIfDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getCliValues($testFile) + { + return ['--encoding=utf-8']; + + }//end getCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 9 => 1, + 10 => 1, + 13 => 1, + 20 => 1, + 24 => 4, + 44 => 1, + 47 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/LowercaseDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/LowercaseDeclarationUnitTest.inc new file mode 100644 index 0000000..1acf3ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/LowercaseDeclarationUnitTest.inc @@ -0,0 +1,24 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowercaseDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\LowercaseDeclarationSniff + */ +class LowercaseDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 1, + 7 => 1, + 9 => 1, + 10 => 1, + 12 => 1, + 14 => 1, + 15 => 1, + 16 => 1, + 20 => 1, + 21 => 1, + 24 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/SwitchDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/SwitchDeclarationUnitTest.inc new file mode 100644 index 0000000..cf39760 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/ControlStructures/SwitchDeclarationUnitTest.inc @@ -0,0 +1,333 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\ControlStructures; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SwitchDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\SwitchDeclarationSniff + */ +class SwitchDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'SwitchDeclarationUnitTest.inc': + return [ + 27 => 1, + 29 => 1, + 34 => 1, + 36 => 1, + 44 => 1, + 48 => 1, + 52 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 58 => 1, + 59 => 1, + 61 => 1, + 62 => 1, + 79 => 1, + 85 => 2, + 88 => 2, + 89 => 2, + 92 => 1, + 95 => 3, + 99 => 1, + 116 => 1, + 122 => 1, + 127 => 2, + 134 => 2, + 135 => 1, + 138 => 1, + 143 => 1, + 144 => 1, + 147 => 1, + 165 => 1, + 172 => 1, + 176 => 2, + 180 => 1, + 192 => 2, + 196 => 1, + 223 => 1, + 266 => 1, + 282 => 1, + 284 => 2, + 322 => 1, + 323 => 1, + 327 => 1, + 329 => 1, + 330 => 1, + ]; + + case 'SwitchDeclarationUnitTest.js': + return [ + 27 => 1, + 29 => 1, + 34 => 1, + 36 => 1, + 44 => 1, + 48 => 1, + 52 => 1, + 54 => 1, + 55 => 1, + 56 => 1, + 58 => 1, + 59 => 1, + 61 => 1, + 62 => 1, + 79 => 1, + 85 => 2, + 88 => 2, + 89 => 2, + 92 => 1, + 95 => 3, + 99 => 1, + 116 => 1, + 122 => 1, + 127 => 2, + 134 => 2, + 135 => 1, + 138 => 1, + 143 => 1, + 144 => 1, + 147 => 1, + 165 => 1, + 172 => 1, + 176 => 2, + 180 => 1, + 192 => 2, + 196 => 1, + 223 => 1, + 266 => 1, + 282 => 1, + 284 => 2, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + if ($testFile === 'SwitchDeclarationUnitTest.js') { + return [273 => 1]; + } + + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.js new file mode 100644 index 0000000..797e0ee --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.js @@ -0,0 +1,2 @@ +alert('hi') +alert('hi'); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.php new file mode 100644 index 0000000..5c7b839 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JSLintUnitTest.php @@ -0,0 +1,74 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Debug; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; +use PHP_CodeSniffer\Config; + +/** + * Unit test class for the JSLint sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Debug\JSLintSniff + */ +class JSLintUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Should this test be skipped for some reason. + * + * @return bool + */ + protected function shouldSkipTest() + { + $jslPath = Config::getExecutablePath('jslint'); + if ($jslPath === null) { + return true; + } + + return false; + + }//end shouldSkipTest() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 1 => 2, + 2 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.js new file mode 100644 index 0000000..797e0ee --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.js @@ -0,0 +1,2 @@ +alert('hi') +alert('hi'); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.php new file mode 100644 index 0000000..e7221ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Debug/JavaScriptLintUnitTest.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Debug; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; +use PHP_CodeSniffer\Config; + +/** + * Unit test class for the JavaScriptLint sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Debug\JavaScriptLintSniff + */ +class JavaScriptLintUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Should this test be skipped for some reason. + * + * @return bool + */ + protected function shouldSkipTest() + { + $jslPath = Config::getExecutablePath('jsl'); + if ($jslPath === null) { + return true; + } + + return false; + + }//end shouldSkipTest() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [2 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.1.inc new file mode 100644 index 0000000..3279edb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.1.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.2.inc new file mode 100644 index 0000000..05be633 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.2.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.3.inc new file mode 100644 index 0000000..ec1b023 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.3.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.4.inc new file mode 100644 index 0000000..ed04564 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.4.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.5.inc new file mode 100644 index 0000000..d777aff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.5.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.php new file mode 100644 index 0000000..fe6388a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Files/FileExtensionUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FileExtension sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Files\FileExtensionSniff + */ +class FileExtensionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FileExtensionUnitTest.1.inc': + return [1 => 1]; + default: + return []; + } + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc new file mode 100644 index 0000000..8e62896 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc @@ -0,0 +1,203 @@ +words[$wordPos-1]) || $this->words[$wordPos-1] !== ' ') { +} else if ($this->tokens[$pos + 1] === "\n") { +} + +if ($pos === count($this->tokens) - 1) { + $file = '...'.substr($file, (($padding * -1) + 3)); +} + +if (substr($basename, -5) !== 'Sniff') { + $i = ($this->_tokens[$i]['parenthesis_closer'] + 1); +} + +$pos = $this->_getShortCommentEndPos(); +if ($pos === -1) { + $stackPtr = ($tokens[$next][$to] - 1); + $stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1); + $var = (($var1 + $var2) + $var3 + $var4) +} + +$commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); +$commentEnd = ($this->_phpcsFile->findNext(T_DOC_COMMENT, ($commentStart + 1), null, true) - 1); +$expected .= '...'.substr($tokens[($stackPtr - 2)]['content'], -5).$tokens[$stackPtr]['content']; + +if (($tokens[$nextToken - 1]['code']) !== T_WHITESPACE) { + $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); +} + +while (($nextSpace = $phpcsFile->findNext(T_WHITESPACE, $nextSpace + 1, $nextBreak)) !== false) { +} + +foreach ($attributes as $id => &$attribute) { +} + +class MyClass +{ + + + public function &myFunction(array &$one, array &$two) + { + + }//end myFunction() + + +}//end class + +if ($index < -1) $index = 0; +if ($index < - 1) $index = 0; + +$three = ceil($one / $two); +$three = ceil(($one / $two) / $four); +$three = ceil($one / ($two / $four)); + +$four = -0.25; + +$three = ceil($one[1] / $two); + +switch ($number % 10) { + case -1: + $suffix = 'st'; + break; +} + +$expectedPermission = array( + 'granted' => 4, + 'denied' => 1, + 'cascade' => TRUE, + 'blockergranted' => 2, + 'blockerdenied' => - 3, + 'effective' => TRUE, + ); + +$value = (int) isset($blah) + 2; +$value = (int) isset($blah) + (int) isset($foo) + (int) isset($bar); + +doSomething(getValue($var, 2)) - $y; + +$codeFiles = array($global => $codeFiles[$global]) + $codeFiles; + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$cntPages = ceil(count($items) / self::ON_PAGE); + +error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); +error_reporting(E_ALL & ~E_NOTICE | ~E_WARNING); +$results = $stmt->fetchAll(\PDO::FETCH_ASSOC | \PDO::FETCH_GROUP | \PDO::FETCH_UNIQUE); +$di = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS); +foo(1 + 2 + 3); + +if (empty($foo[-1]) === true) { + $foo[-1] = 'foo'; +} + +try { +} catch (AException | BException $e) { +} + +$var = $foo['blah'] + []; + +$a = 2 * ${x} - ${minus}; + +$foo = $bar ?? $baz ?? ''; + +$foo = $myString{-1}; + +$value = (binary) $blah + b"binary $foo"; + +$test = (1 * static::TEST); +$test = myfunc(1 * static::TEST); + +$errorPos = $params[$x]?->getLine() + $commentStart; + +$foo = $this->gmail ?? $this->gmail = new Google_Service_Gmail($this->google); + +exit -1; + +$expr = match ($number - 10) { + -1 => 0, +}; + +$expr = match ($number % 10) { + 1 => 2 * $num, +}; + +$expr = match (true) { + $num * 100 > 500 => 'expression in key', +}; + +// PHP 8.0 named parameters. +if ($pos === count(value: $this->tokens) - 1) { + $file = '...'.substr(string: $file, offset: $padding * -1 + 3); +} + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$cntPages = ceil(count($items) / parent::ON_PAGE); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc.fixed new file mode 100644 index 0000000..9fa0216 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.inc.fixed @@ -0,0 +1,203 @@ +words[($wordPos-1)]) || $this->words[($wordPos-1)] !== ' ') { +} else if ($this->tokens[($pos + 1)] === "\n") { +} + +if ($pos === (count($this->tokens) - 1)) { + $file = '...'.substr($file, (($padding * -1) + 3)); +} + +if (substr($basename, -5) !== 'Sniff') { + $i = ($this->_tokens[$i]['parenthesis_closer'] + 1); +} + +$pos = $this->_getShortCommentEndPos(); +if ($pos === -1) { + $stackPtr = ($tokens[$next][$to] - 1); + $stackPtr = ($tokens[$next][$pattern[$i]['to']] + 1); + $var = (($var1 + $var2) + $var3 + $var4) +} + +$commentStart = ($phpcsFile->findPrevious(T_DOC_COMMENT, ($commentEnd - 1), null, true) + 1); +$commentEnd = ($this->_phpcsFile->findNext(T_DOC_COMMENT, ($commentStart + 1), null, true) - 1); +$expected .= '...'.substr($tokens[($stackPtr - 2)]['content'], -5).$tokens[$stackPtr]['content']; + +if (($tokens[($nextToken - 1)]['code']) !== T_WHITESPACE) { + $errorPos = ($params[(count($params) - 1)]->getLine() + $commentStart); +} + +while (($nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), $nextBreak)) !== false) { +} + +foreach ($attributes as $id => &$attribute) { +} + +class MyClass +{ + + + public function &myFunction(array &$one, array &$two) + { + + }//end myFunction() + + +}//end class + +if ($index < -1) $index = 0; +if ($index < - 1) $index = 0; + +$three = ceil($one / $two); +$three = ceil(($one / $two) / $four); +$three = ceil($one / ($two / $four)); + +$four = -0.25; + +$three = ceil($one[1] / $two); + +switch ($number % 10) { + case -1: + $suffix = 'st'; + break; +} + +$expectedPermission = array( + 'granted' => 4, + 'denied' => 1, + 'cascade' => TRUE, + 'blockergranted' => 2, + 'blockerdenied' => - 3, + 'effective' => TRUE, + ); + +$value = ((int) isset($blah) + 2); +$value = ((int) isset($blah) + (int) isset($foo) + (int) isset($bar)); + +(doSomething(getValue($var, 2)) - $y); + +$codeFiles = (array($global => $codeFiles[$global]) + $codeFiles); + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$cntPages = ceil(count($items) / self::ON_PAGE); + +error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); +error_reporting(E_ALL & ~E_NOTICE | ~E_WARNING); +$results = $stmt->fetchAll(\PDO::FETCH_ASSOC | \PDO::FETCH_GROUP | \PDO::FETCH_UNIQUE); +$di = new \RecursiveDirectoryIterator($path, (\RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS)); +foo(1 + 2 + 3); + +if (empty($foo[-1]) === true) { + $foo[-1] = 'foo'; +} + +try { +} catch (AException | BException $e) { +} + +$var = ($foo['blah'] + []); + +$a = 2 * ${x} - ${minus}; + +$foo = ($bar ?? $baz ?? ''); + +$foo = $myString{-1}; + +$value = ((binary) $blah + b"binary $foo"); + +$test = (1 * static::TEST); +$test = myfunc(1 * static::TEST); + +$errorPos = ($params[$x]?->getLine() + $commentStart); + +$foo = ($this->gmail ?? $this->gmail = new Google_Service_Gmail($this->google)); + +exit -1; + +$expr = match ($number - 10) { + -1 => 0, +}; + +$expr = match ($number % 10) { + 1 => (2 * $num), +}; + +$expr = match (true) { + ($num * 100) > 500 => 'expression in key', +}; + +// PHP 8.0 named parameters. +if ($pos === (count(value: $this->tokens) - 1)) { + $file = '...'.substr(string: $file, offset: ($padding * -1 + 3)); +} + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +$cntPages = ceil(count($items) / parent::ON_PAGE); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js new file mode 100644 index 0000000..92ed803 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js @@ -0,0 +1,118 @@ +value = (one + two); +value = one + two; + +value = (one - two); +value = one - two; + +value = (one * two); +value = one * two; + +value = (one / two); +value = one / two; + +value = (one % two); +value = one % two; + +value = (one + two + three); +value = one + two + three; +value = (one + (two + three)); +value = one + (two + three); + +value++; +value--; +value = -1; +value = - 1; + +value = (1 + 2); +value = 1 + 2; + +value = (1 - 2); +value = 1 - 2; + +value = (1 * 2); +value = 1 * 2; + +value = (1 / 2); +value = 1 / 2; + +value = (1 % 2); +value = 1 % 2; + +value = (1 + 2 + 3); +value = 1 + 2 + 3; +value = (1 + (2 + 3)); +value = 1 + (2 + 3); + +value = one + 2 + 3 - (four * five * (6 + 7)) + nine + 2; +value = myFunction(tokens[stackPtr - 1]); + +for (i = 1 + 2; i < 4 + 5; i++) { +} + +function myFunction() +{ + value = (one + 1) + (two + 2) + (myFunction() + 2); + value = myFunction() + 2; + value = (myFunction(mvar) + myFunction2(mvar)); + return -1; +} + +params['mode'] = id.replace(/WidgetType/, ''); + +if (index < -1) index = 0; +if (index < - 1) index = 0; + +var classN = prvId.replace(/\./g, '-'); + +three = myFunction(one / two); +three = myFunction((one / two) / four); +three = myFunction(one / (two / four)); + +four = -0.25; + +id = id.replace(/row\/:/gi, ''); +return /MSIE/.test(navigator.userAgent); + +var re = new RegExp(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim); + +var options = { + minVal: -1, + maxVal: -1 +}; + +stepWidth = Math.round(this.width / 5); + +date.setMonth(d[2] - 1); + +switch (number % 10) { + case -1: + suffix = 'st'; + break; +} + +var pathSplit = ipt.value.split(/\/|\\/); + +if (pairs[i].search(/=/) !== -1) { +} + +if (urlValue.search(/[a-zA-z]+:\/\//) !== 0) { +} + +if (urlValue.search(/[a-zA-z]+:\/\/*/) !== 0) { +} + +if (!value || /^\s*$/.test(value)) { + return true; +} + +parseInt(dfx.attr(selectors[idx], 'elemOffsetTop'), 10) - scrollCoords.y + 'px' + +if (something === true + ^ somethingElse === true +) { + return false; +} + +if (true === /^\d*\.?\d*$/.test(input)) return true; + +if ( ! /^(?:a|select)$/i.test( element.tagName ) ) return true; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js.fixed new file mode 100644 index 0000000..04e35d9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.js.fixed @@ -0,0 +1,118 @@ +value = (one + two); +value = one + two; + +value = (one - two); +value = (one - two); + +value = (one * two); +value = (one * two); + +value = (one / two); +value = (one / two); + +value = (one % two); +value = (one % two); + +value = (one + two + three); +value = one + two + three; +value = (one + (two + three)); +value = one + (two + three); + +value++; +value--; +value = -1; +value = - 1; + +value = (1 + 2); +value = 1 + 2; + +value = (1 - 2); +value = (1 - 2); + +value = (1 * 2); +value = (1 * 2); + +value = (1 / 2); +value = (1 / 2); + +value = (1 % 2); +value = (1 % 2); + +value = (1 + 2 + 3); +value = 1 + 2 + 3; +value = (1 + (2 + 3)); +value = 1 + (2 + 3); + +value = one + 2 + (3 - (four * five * (6 + 7))) + nine + 2; +value = myFunction(tokens[(stackPtr - 1)]); + +for (i = 1 + 2; i < 4 + 5; i++) { +} + +function myFunction() +{ + value = (one + 1) + (two + 2) + (myFunction() + 2); + value = myFunction() + 2; + value = (myFunction(mvar) + myFunction2(mvar)); + return -1; +} + +params['mode'] = id.replace(/WidgetType/, ''); + +if (index < -1) index = 0; +if (index < - 1) index = 0; + +var classN = prvId.replace(/\./g, '-'); + +three = myFunction(one / two); +three = myFunction((one / two) / four); +three = myFunction(one / (two / four)); + +four = -0.25; + +id = id.replace(/row\/:/gi, ''); +return /MSIE/.test(navigator.userAgent); + +var re = new RegExp(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim); + +var options = { + minVal: -1, + maxVal: -1 +}; + +stepWidth = Math.round(this.width / 5); + +date.setMonth(d[2] - 1); + +switch (number % 10) { + case -1: + suffix = 'st'; + break; +} + +var pathSplit = ipt.value.split(/\/|\\/); + +if (pairs[i].search(/=/) !== -1) { +} + +if (urlValue.search(/[a-zA-z]+:\/\//) !== 0) { +} + +if (urlValue.search(/[a-zA-z]+:\/\/*/) !== 0) { +} + +if (!value || /^\s*$/.test(value)) { + return true; +} + +(parseInt(dfx.attr(selectors[idx], 'elemOffsetTop'), 10) - scrollCoords.y) + 'px' + +if (something === true + ^ somethingElse === true +) { + return false; +} + +if (true === /^\d*\.?\d*$/.test(input)) return true; + +if ( ! /^(?:a|select)$/i.test( element.tagName ) ) return true; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.php new file mode 100644 index 0000000..ee5af1b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Formatting/OperatorBracketUnitTest.php @@ -0,0 +1,121 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Formatting; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the OperatorBracket sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Formatting\OperatorBracketSniff + */ +class OperatorBracketUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'OperatorBracketUnitTest.inc': + return [ + 3 => 1, + 6 => 1, + 9 => 1, + 12 => 1, + 15 => 1, + 18 => 2, + 20 => 1, + 25 => 1, + 28 => 1, + 31 => 1, + 34 => 1, + 37 => 1, + 40 => 1, + 43 => 2, + 45 => 1, + 47 => 5, + 48 => 1, + 50 => 2, + 55 => 2, + 56 => 1, + 63 => 2, + 64 => 1, + 67 => 1, + 86 => 1, + 90 => 1, + 109 => 1, + 130 => 1, + 134 => 1, + 135 => 2, + 137 => 1, + 139 => 1, + 150 => 1, + 161 => 1, + 163 => 2, + 165 => 2, + 169 => 1, + 174 => 1, + 176 => 1, + 185 => 1, + 189 => 1, + 193 => 1, + 194 => 2, + ]; + + case 'OperatorBracketUnitTest.js': + return [ + 5 => 1, + 8 => 1, + 11 => 1, + 14 => 1, + 24 => 1, + 30 => 1, + 33 => 1, + 36 => 1, + 39 => 1, + 46 => 1, + 47 => 1, + 63 => 1, + 108 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc new file mode 100644 index 0000000..33564e2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc @@ -0,0 +1,111 @@ + $a($b); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..68fb1c1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.inc.fixed @@ -0,0 +1,111 @@ + $a($b); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.php new file mode 100644 index 0000000..2981af5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationArgumentSpacingUnitTest.php @@ -0,0 +1,91 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionDeclarationArgumentSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationArgumentSpacingSniff + */ +class FunctionDeclarationArgumentSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 2, + 7 => 2, + 8 => 2, + 9 => 2, + 11 => 2, + 13 => 7, + 14 => 2, + 15 => 2, + 16 => 4, + 18 => 2, + 35 => 2, + 36 => 2, + 44 => 2, + 45 => 1, + 46 => 1, + 51 => 2, + 53 => 2, + 55 => 1, + 56 => 1, + 58 => 1, + 73 => 7, + 76 => 1, + 77 => 1, + 81 => 1, + 89 => 2, + 92 => 1, + 93 => 1, + 94 => 1, + 95 => 1, + 99 => 11, + 100 => 2, + 101 => 2, + 102 => 2, + 106 => 1, + 107 => 2, + 111 => 3, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.inc new file mode 100644 index 0000000..0cde113 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDeclarationUnitTest.inc @@ -0,0 +1,75 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationSniff + */ +class FunctionDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 55 => 1, + 68 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.inc new file mode 100644 index 0000000..27102d0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.inc @@ -0,0 +1,6 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.php new file mode 100644 index 0000000..68ee6be --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/FunctionDuplicateArgumentUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionDuplicateArgument sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDuplicateArgumentSniff + */ +class FunctionDuplicateArgumentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 4 => 2, + 5 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.inc new file mode 100644 index 0000000..b7b7f20 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.inc @@ -0,0 +1,17 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.php new file mode 100644 index 0000000..03af0b0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/GlobalFunctionUnitTest.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the GlobalFunction sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\GlobalFunctionSniff + */ +class GlobalFunctionUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [2 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc new file mode 100644 index 0000000..4e86833 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc @@ -0,0 +1,28 @@ + $x; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc.fixed new file mode 100644 index 0000000..48c9977 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.inc.fixed @@ -0,0 +1,28 @@ + $x; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.php new file mode 100644 index 0000000..11b21ba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/LowercaseFunctionKeywordsUnitTest.php @@ -0,0 +1,63 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowercaseFunctionKeywords sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\LowercaseFunctionKeywordsSniff + */ +class LowercaseFunctionKeywordsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 16 => 1, + 17 => 1, + 20 => 1, + 21 => 1, + 22 => 1, + 23 => 1, + 24 => 3, + 25 => 4, + 28 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/MultiLineFunctionDeclarationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/MultiLineFunctionDeclarationUnitTest.inc new file mode 100644 index 0000000..811c56e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Functions/MultiLineFunctionDeclarationUnitTest.inc @@ -0,0 +1,304 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Functions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MultiLineFunctionDeclaration sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff + */ +class MultiLineFunctionDeclarationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile === 'MultiLineFunctionDeclarationUnitTest.inc') { + $errors = [ + 2 => 1, + 3 => 1, + 4 => 2, + 5 => 1, + 7 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 16 => 1, + 36 => 1, + 43 => 2, + 48 => 1, + 81 => 1, + 82 => 2, + 88 => 1, + 102 => 2, + 137 => 1, + 141 => 2, + 142 => 1, + 158 => 1, + 160 => 1, + 182 => 2, + 186 => 2, + 190 => 2, + 194 => 1, + 195 => 1, + 233 => 1, + 234 => 1, + 235 => 1, + 236 => 1, + 244 => 1, + 245 => 1, + 246 => 1, + 247 => 1, + 248 => 1, + 249 => 1, + 250 => 1, + 251 => 1, + 252 => 1, + 253 => 1, + 254 => 1, + ]; + } else { + $errors = [ + 2 => 1, + 3 => 1, + 4 => 2, + 5 => 1, + 7 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 16 => 1, + 26 => 1, + 36 => 1, + 43 => 2, + 48 => 1, + 65 => 1, + ]; + }//end if + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.inc new file mode 100644 index 0000000..aacef34 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.inc @@ -0,0 +1,27 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.php new file mode 100644 index 0000000..c3dce6c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidFunctionNameUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidFunctionName sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\NamingConventions\ValidFunctionNameSniff + */ +class ValidFunctionNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 9 => 1, + 11 => 1, + 12 => 1, + 13 => 1, + 14 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.inc new file mode 100644 index 0000000..87c3bdf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -0,0 +1,157 @@ +varName2; +echo $this->var_name2; +echo $this->varname2; +echo $this->_varName2; +echo $object->varName2; +echo $object->var_name2; +echo $object_name->varname2; +echo $object_name->_varName2; + +echo $this->myFunction($one, $two); +echo $object->myFunction($one_two); + +$error = "format is \$GLOBALS['$varName']"; + +echo $_SESSION['var_name']; +echo $_FILES['var_name']; +echo $_ENV['var_name']; +echo $_COOKIE['var_name']; + +$XML = 'hello'; +$myXML = 'hello'; +$XMLParser = 'hello'; +$xmlParser = 'hello'; + +echo "{$_SERVER['HOSTNAME']} $var_name"; + +// Need to be the last thing in this test file. +$obj->$classVar = $prefix.'-'.$type; + +class foo +{ + const bar = <<varName; +echo $obj?->var_name; +echo $obj?->varname; +echo $obj?->_varName; + +enum SomeEnum +{ + public function foo($foo, $_foo, $foo_bar) { + $bar = 1; + $_bar = 2; + $bar_foo = 3; + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.php new file mode 100644 index 0000000..0638d9d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -0,0 +1,93 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidVariableName sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\NamingConventions\ValidVariableNameSniff + */ +class ValidVariableNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + $errors = [ + 3 => 1, + 5 => 1, + 10 => 1, + 12 => 1, + 15 => 1, + 17 => 1, + 20 => 1, + 22 => 1, + 25 => 1, + 27 => 1, + 31 => 1, + 33 => 1, + 36 => 1, + 37 => 1, + 39 => 1, + 42 => 1, + 44 => 1, + 53 => 1, + 58 => 1, + 62 => 1, + 63 => 1, + 64 => 1, + 67 => 1, + 81 => 1, + 106 => 1, + 107 => 2, + 108 => 1, + 111 => 1, + 112 => 1, + 113 => 1, + 114 => 1, + 123 => 1, + 138 => 1, + 141 => 1, + 146 => 1, + 152 => 1, + 155 => 1, + ]; + + return $errors; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.js new file mode 100644 index 0000000..1c61fbf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.js @@ -0,0 +1,37 @@ +function test(id) +{ + + this.id = id; + +} +/**/ +test.prototype = { + init: function() + { + var x = {}; + x.name = 'test'; + x['phone'] = 123124324; + var t = ['test', 'this'].join(''); + var y = ['test'].join(''); + var a = x[0]; + var z = x[x['name']]; + var p = x[x.name]; + } + +}; + +function test() { + this.errors['step_' + step] = errors; + this.errors['test'] = x; + this.errors['test' + 10] = x; + this.errors['test' + y] = x; + this.errors['test' + 'blah'] = x; + this.errors[y] = x; + this.errors[y + z] = x; + this.permissions['workflow.cancel'] = x; +} + +if (child.prototype) { + above.prototype['constructor'] = parent; + child.prototype['super'] = new above(); +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.php new file mode 100644 index 0000000..f3a71f7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/DisallowObjectStringIndexUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowObjectStringIndex sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects\DisallowObjectStringIndexSniff + */ +class DisallowObjectStringIndexUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + if ($testFile !== 'DisallowObjectStringIndexUnitTest.js') { + return []; + } + + return [ + 13 => 1, + 17 => 1, + 25 => 1, + 35 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.inc new file mode 100644 index 0000000..725c60e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.inc @@ -0,0 +1,53 @@ + new MyClass()); +$object->myFunction(new MyClass()); + +throw new MyException($msg); + +function foo() { return new MyClass(); } + +$doodad = $x ? new Foo : new Bar; + +function returnFn() { + $fn = fn($x) => new MyClass(); +} + +function returnMatch() { + $match = match($x) { + 0 => new MyClass() + } +} + +// Issue 3333. +$time2 ??= new \DateTime(); +$time3 = $time1 ?? new \DateTime(); +$time3 = $time1 ?? $time2 ?? new \DateTime(); + +function_call($time1 ?? new \DateTime()); +$return = function_call($time1 ?? new \DateTime()); // False negative depending on interpretation of the sniff. + +function returnViaTernary() { + return ($y == false ) ? ($x === true ? new Foo : new Bar) : new FooBar; +} + +function nonAssignmentTernary() { + if (($x ? new Foo() : new Bar) instanceof FooBar) { + // Do something. + } +} + +// Test for tokenizer issue #3789. +$a = $b !== null + ? match ($c) { + default => 5, + } + : new Foo; + +// Intentional parse error. This must be the last test in the file. +function new +?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.php new file mode 100644 index 0000000..231dd60 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectInstantiationUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ObjectInstantiation sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects\ObjectInstantiationSniff + */ +class ObjectInstantiationUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 8 => 1, + 31 => 1, + 39 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js new file mode 100644 index 0000000..28bf85a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js @@ -0,0 +1,47 @@ +this.request({ action: 'getTypeFormatContents', }); + +addTypeFormatButton.addClickEvent(function() { + self.addNewTypeFormat(); +}); + +var x = {}; + +var y = { + VarOne : 'If you ask me, thats if you ask', + VarTwo : ['Alonzo played you', 'for a fool', 'esse'], + VarThree: function(arg) { + console.info(1); + } +}; + +var z = { + VarOne : 'If you ask me, thats if you ask', + VarTwo : ['Alonzo played you', 'for a fool', 'esse'], + VarThree: function(arg) { + console.info(1); + }, +}; + +var x = function() { + console.info(2); +}; + +AssetListingEditWidgetType.prototype = { + init: function(data, assetid, editables) + { + } +}; + +AssetListingEditWidgetType.prototype = { + init: function(data, assetid, editables) + { + }, +}; + +AssetListingEditWidgetType.prototype = { + // phpcs: disable Standard.Cat.SniffName -- testing annotation between closing brace and comma + init: function(data, assetid, editables) + { + }, + // phpcs:enable +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js.fixed new file mode 100644 index 0000000..df548c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.js.fixed @@ -0,0 +1,47 @@ +this.request({ action: 'getTypeFormatContents' }); + +addTypeFormatButton.addClickEvent(function() { + self.addNewTypeFormat(); +}); + +var x = {}; + +var y = { + VarOne : 'If you ask me, thats if you ask', + VarTwo : ['Alonzo played you', 'for a fool', 'esse'], + VarThree: function(arg) { + console.info(1); + } +}; + +var z = { + VarOne : 'If you ask me, thats if you ask', + VarTwo : ['Alonzo played you', 'for a fool', 'esse'], + VarThree: function(arg) { + console.info(1); + } +}; + +var x = function() { + console.info(2); +}; + +AssetListingEditWidgetType.prototype = { + init: function(data, assetid, editables) + { + } +}; + +AssetListingEditWidgetType.prototype = { + init: function(data, assetid, editables) + { + } +}; + +AssetListingEditWidgetType.prototype = { + // phpcs: disable Standard.Cat.SniffName -- testing annotation between closing brace and comma + init: function(data, assetid, editables) + { + } + // phpcs:enable +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.php new file mode 100644 index 0000000..347c69a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Objects/ObjectMemberCommaUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Objects; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ObjectMemberComma sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Objects\ObjectMemberCommaSniff + */ +class ObjectMemberCommaUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 1 => 1, + 22 => 1, + 38 => 1, + 45 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.inc new file mode 100644 index 0000000..8522438 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.inc @@ -0,0 +1,138 @@ + + 0)) { +} + +myFunction($var1 === true ? "" : "foobar"); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.js new file mode 100644 index 0000000..048223b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.js @@ -0,0 +1,71 @@ +if (value === TRUE) { +} else if (value === FALSE) { +} + +if (value == TRUE) { +} else if (value == FALSE) { +} + +if (value) { +} else if (!value) { +} + +if (value.isSomething === TRUE) { +} else if (myFunction(value) === FALSE) { +} + +if (value.isSomething == TRUE) { +} else if (myFunction(value) == FALSE) { +} + +if (value.isSomething) { +} else if (!myFunction(value)) { +} + +if (value === TRUE || other === FALSE) { +} + +if (value == TRUE || other == FALSE) { +} + +if (value || !other) { +} + +if (one === TRUE || two === TRUE || three === FALSE || four === TRUE) { +} + +if (one || two || !three || four) { +} + +while (one == true) { +} + +while (one === true) { +} + +do { +} while (one == true); + +do { +} while (one === true); + +for (one = 10; one != 0; one--) { +} + +for (one = 10; one !== 0; one--) { +} + +for (type in types) { +} + +variable = (variable2 === true) ? variable1 : "foobar"; + +variable = (variable2 == true) ? variable1 : "foobar"; + +variable = (variable2 === false) ? variable1 : "foobar"; + +variable = (variable2 == false) ? variable1 : "foobar"; + +variable = (variable2 === 0) ? variable1 : "foobar"; + +variable = (variable2 == 0) ? variable1 : "foobar"; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.php new file mode 100644 index 0000000..ffaf905 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ComparisonOperatorUsageUnitTest.php @@ -0,0 +1,105 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Operators; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ComparisonOperatorUsage sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators\ComparisonOperatorUsageSniff + */ +class ComparisonOperatorUsageUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ComparisonOperatorUsageUnitTest.inc': + return [ + 6 => 1, + 7 => 1, + 10 => 1, + 11 => 1, + 18 => 1, + 19 => 1, + 22 => 1, + 23 => 1, + 29 => 2, + 32 => 2, + 38 => 4, + 47 => 2, + 69 => 1, + 72 => 1, + 75 => 1, + 78 => 1, + 80 => 1, + 82 => 1, + 83 => 1, + 89 => 1, + 92 => 1, + 100 => 1, + 106 => 1, + 112 => 1, + 123 => 1, + 127 => 1, + 131 => 1, + 135 => 1, + ]; + + case 'ComparisonOperatorUsageUnitTest.js': + return [ + 5 => 1, + 6 => 1, + 17 => 1, + 18 => 1, + 28 => 2, + 40 => 1, + 47 => 1, + 52 => 1, + 63 => 1, + 67 => 1, + 71 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.inc new file mode 100644 index 0000000..a4f82d1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.inc @@ -0,0 +1,42 @@ +i++).$id; +$id = $obj?->i++.$id; +$id = $obj?->i++*10; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.php new file mode 100644 index 0000000..0393baf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/IncrementDecrementUsageUnitTest.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Operators; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the IncrementDecrementUsage sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators\IncrementDecrementUsageSniff + */ +class IncrementDecrementUsageUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 6 => 1, + 12 => 1, + 16 => 1, + 25 => 1, + 26 => 1, + 27 => 1, + 29 => 1, + 31 => 1, + 41 => 1, + 42 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.inc new file mode 100644 index 0000000..328ccc5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.inc @@ -0,0 +1,28 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.php new file mode 100644 index 0000000..e91f951 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Operators/ValidLogicalOperatorsUnitTest.php @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Operators; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidLogicalOperators sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Operators\ValidLogicalOperatorsSniff + */ +class ValidLogicalOperatorsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 11 => 1, + 17 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.css new file mode 100644 index 0000000..94cc8f2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.css @@ -0,0 +1,23 @@ +/* CSS Document */ + +body { +font-family: Arial, Helvetica, sans-serif; +margin : 40px 0 0 0; +padding : 0; +/*background: #8FB7DB url(login_glow_bg.jpg) no-repeat 30% 0;*/ +background: #8FB7DB url(diag_lines_bg.gif) top left; +} + +#login-container { + margin-left: -225px; + margin-top: -161px; + position:absolute; + top :50%; + /*left :50%;*/ + width:450px; +} + +#cacheConfig-dayLabel, #cacheConfig-hourLabel, #cacheConfig-minuteLabel { + float: left; + padding-right: 8px; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.inc new file mode 100644 index 0000000..121240a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.inc @@ -0,0 +1,158 @@ + + * + * Title + * Contents + * + * ... + * + * + * + * + * @return void + */ + +/* + [^\'"] +*/ + +// http://www.google.com + +// Base config function. + +// function () + +// T_STRING is not a function call or not listed in _getFunctionListWithCallableArgument(). + + // function myFunction( $param ) + // { + // do_something(); + // }//end myFunction() + // + +/* +function myFunction( $param ) +{ + // phpcs:disable Standard.Category.Sniff -- for reasons. + if ( preg_match( '`[abc]`', $param ) > 0 ) { + do_something(); + } + // phpcs:enable Standard.Category.Sniff -- for reasons. + +}//end myFunction() +*/ + + /* + * function myFunction( $param ) // @phpcs:ignore Standard.Category.Sniff -- for reasons. + * { + * + * }//end myFunction() + */ + + /* + * function myFunction( $param ) + * { + * // phpcs:disable Standard.Category.Sniff -- for reasons. + * if ( preg_match( '`[abc]`', $param ) > 0 ) { + * do_something(); + * } + * // phpcs:enable Standard.Category.Sniff -- for reasons. + * + * }//end myFunction() + */ + + // function myFunction( $param ) + // { + // phpcs:disable Standard.Category.Sniff -- for reasons. + // do_something(); + // phpcs:enable Standard.Category.Sniff -- for reasons. + // }//end myFunction() + // + +echo 'something'; // @codeCoverageIgnore +echo 'something'; // @codeCoverageIgnoreStart +echo 'something'; // @SuppressWarnings(PHPMD.UnusedLocalVariable) + +// Ok! + +/* Go! */ + +// ISO-639-3 + + // But override with a different text if any. + /* + $id = intval( str_replace( 'hook_name', '', $order_method['method_id'] ) ); + if ( ! empty( $id ) ) { + $info_text = get_post_meta( $location_id, 'meta_name' ); + + if ( ! empty( $info_text ) ) { + $text = $info_text; + } + + } + */ + // function() { $a = $b; }; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.php new file mode 100644 index 0000000..148d138 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/CommentedOutCodeUnitTest.php @@ -0,0 +1,80 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the CommentedOutCode sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\CommentedOutCodeSniff + */ +class CommentedOutCodeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'CommentedOutCodeUnitTest.inc': + return [ + 6 => 1, + 8 => 1, + 15 => 1, + 19 => 1, + 87 => 1, + 91 => 1, + 97 => 1, + 109 => 1, + 116 => 1, + 128 => 1, + 147 => 1, + 158 => 1, + ]; + + case 'CommentedOutCodeUnitTest.css': + return [ + 7 => 1, + 16 => 1, + ]; + + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.inc new file mode 100644 index 0000000..4701c23 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.inc @@ -0,0 +1,27 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.php new file mode 100644 index 0000000..d2122d4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowBooleanStatementUnitTest.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowBooleanStatement sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DisallowBooleanStatementSniff + */ +class DisallowBooleanStatementUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 8 => 1, + 13 => 1, + 15 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.inc new file mode 100644 index 0000000..a07047b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.inc @@ -0,0 +1,83 @@ +nextSibling; $node; $node = $node->nextSibling) { + if ($node->nodeType !== XML_ELEMENT_NODE) { + continue; + } + + for ($node = $fields->nextSibling; $node; $node = $node->nextSibling) { + if ($node->nodeType !== XML_ELEMENT_NODE) { + continue; + } + } +} + +$a = $b ? $c : $d; +$a = $b === true ? $c : $d; + +$this->_args = $this->_getArgs(($_SERVER['argv'] ?? [])); +$args = ($_SERVER['argv'] ?? []); + +$a = [ + 'a' => ($foo) ? $foo : $bar, +]; + +$a = [ + 'a' => ($foo) ? fn() => return 1 : fn() => return 2, +]; + +$var = $foo->something(!$var); +$var = $foo?->something(!$var); + +$callback = function ($value) { + if ($value > 10) { + return false; + } +}; + +function issue3616() { + $food = 'cake'; + + $returnValue = match (true) { + $food === 'apple' => 'This food is an apple', + $food === 'bar' => 'This food is a bar', + $food === 'cake' => 'This food is a cake', + }; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.php new file mode 100644 index 0000000..e26f7d0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowComparisonAssignmentUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowComparisonAssignment sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DisallowComparisonAssignmentSniff + */ +class DisallowComparisonAssignmentUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 10 => 1, + 52 => 1, + 53 => 1, + 58 => 1, + 62 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.inc new file mode 100644 index 0000000..f57e071 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.inc @@ -0,0 +1,18 @@ + $x; + +$b = fn ($b) => $b ? true : false; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.js new file mode 100644 index 0000000..56387c0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.js @@ -0,0 +1,2 @@ +x = (x?a:x); +id = id.replace(/row\/:/gi, ''); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.php new file mode 100644 index 0000000..7e78e97 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowInlineIfUnitTest.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowObEndFlush sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DisallowInlineIfSniff + */ +class DisallowInlineIfUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowInlineIfUnitTest.inc': + return [ + 8 => 1, + 18 => 1, + ]; + + case 'DisallowInlineIfUnitTest.js': + return [1 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.inc new file mode 100644 index 0000000..f657fb4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.inc @@ -0,0 +1,110 @@ +fetch(PDO::FETCH_NUM)) { + $result[$row[0]] = array(); + $result[$row[0]][] = $current; + + self::$_inTransaction = TRUE; + parent::$_inTransaction = TRUE; + static::$_inTransaction = TRUE; + $$varName = $varValue; + } + +}//end getVar() + +class myClass +{ + private static $_dbh = NULL; + public $dbh = NULL; + protected $dbh = NULL; + var $dbh = NULL; // Old PHP4 compatible code. +} + +A::$a = 'b'; +\A::$a = 'c'; +\A\B\C::$d = 'd'; +B\C::$d = 'e'; + +@$a = 1; + +$a = []; +foreach ($a as $b) + $c = 'd'; + +$var = $var2; +list ($a, $b) = explode(',', $c); +$var1 ? $var2 = 0 : $var2 = 1; + +$obj->$classVar = $prefix.'-'.$type; + +$closureWithDefaultParamter = function(array $testArray=array()) {}; +?> + + + 10, + false => 0 + }, +]; + +$arrow_function = fn ($a = null) => $a; + +function ($html) { + $regEx = '/regexp/'; + + return preg_replace_callback($regEx, function ($matches) { + [$all] = $matches; + return $all; + }, $html); +}; + + +function () { + $a = false; + + some_label: + + $b = getB(); +}; + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.php new file mode 100644 index 0000000..c89656d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowMultipleAssignmentsUnitTest.php @@ -0,0 +1,63 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowMultipleAssignments sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DisallowMultipleAssignmentsSniff + */ +class DisallowMultipleAssignmentsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 5 => 2, + 7 => 1, + 9 => 1, + 12 => 1, + 14 => 1, + 15 => 1, + 79 => 1, + 85 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.inc new file mode 100644 index 0000000..56802e3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.inc @@ -0,0 +1,58 @@ +children); $i++) { +} + + + +for ($i = 0; $i < sizeof($array); $i++) { +} + +$num = sizeof($array); + +while ($i < sizeof($array)) { +} + +do { +} while ($i < sizeof($array)); + +for ($i = 0; $i < sizeof($this->children); $i++) { +} + + + + +for ($i = 0; $i < strlen($string); $i++) { +} + +$num = strlen($string); + +while ($i < strlen($string)) { +} + +do { +} while ($i < strlen($string)); + +for ($i = 0; $i < strlen($this->string); $i++) { +} + +for ($i = sizeof($array); $i > 0; $i--) { +} + +do { + echo $a->count; + $a->count--; +} while($a->count); + +for ($i = 0; $i < $a->count; $i++) {} +for ($i = 0; $i < $a?->count; $i++) {} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.js new file mode 100644 index 0000000..8f7f7b9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.js @@ -0,0 +1,13 @@ +for (var i = 0; i < permissions.length; i++) { + // Code here. +} + +var permLen = permissions.length; +for (var length = 0; i < permLen; i++) { + // Code here. +} + +var myArray = [1, 2, 3, 4]; +for (var i = myArray.length; i >= 0; i--) { + var x = i; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.php new file mode 100644 index 0000000..8ec0b73 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DisallowSizeFunctionsInLoopsUnitTest.php @@ -0,0 +1,77 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DisallowSizeFunctionsInLoops sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DisallowSizeFunctionsInLoopsSniff + */ +class DisallowSizeFunctionsInLoopsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'DisallowSizeFunctionsInLoopsUnitTest.inc': + return [ + 2 => 1, + 7 => 1, + 11 => 1, + 13 => 1, + 18 => 1, + 23 => 1, + 27 => 1, + 29 => 1, + 35 => 1, + 40 => 1, + 44 => 1, + 46 => 1, + ]; + + case 'DisallowSizeFunctionsInLoopsUnitTest.js': + return [1 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DiscouragedFunctionsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DiscouragedFunctionsUnitTest.inc new file mode 100644 index 0000000..3c875d0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/DiscouragedFunctionsUnitTest.inc @@ -0,0 +1,7 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DiscouragedFunctions sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\DiscouragedFunctionsSniff + */ +class DiscouragedFunctionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 2 => 1, + 3 => 1, + 4 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc new file mode 100644 index 0000000..c61d5a3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc @@ -0,0 +1,119 @@ + + + +<?php echo $title ?> + + + + + hello + + + + + + + + + + + + + + + + + + + + + +section as $section) { + ?> + + + + + + section as $section) { + ?> +
    + + + + + + + + +?> + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc.fixed new file mode 100644 index 0000000..5b43d84 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.inc.fixed @@ -0,0 +1,119 @@ + + + +<?php echo $title; ?> + + + + + hello + + + + + + + + + + + + + + + + + + + +section as $section) { + ?> +
    + + + + + section as $section) { + ?> +
    + + + + + + + + + + + + +?> + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.php new file mode 100644 index 0000000..dd13cb1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EmbeddedPhpUnitTest.php @@ -0,0 +1,83 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EmbeddedPhp sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EmbeddedPhpSniff + */ +class EmbeddedPhpUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 12 => 1, + 18 => 1, + 19 => 2, + 20 => 1, + 21 => 1, + 22 => 3, + 24 => 1, + 26 => 1, + 29 => 1, + 30 => 1, + 31 => 1, + 34 => 1, + 36 => 1, + 40 => 1, + 41 => 1, + 44 => 1, + 45 => 1, + 49 => 1, + 59 => 1, + 63 => 1, + 93 => 1, + 94 => 2, + 100 => 1, + 102 => 1, + 112 => 1, + 113 => 1, + 116 => 1, + 117 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.inc new file mode 100644 index 0000000..ee4c73e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.inc @@ -0,0 +1,5 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.php new file mode 100644 index 0000000..277cef9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/EvalUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the Eval sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EvalSniff + */ +class EvalUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 2 => 1, + 4 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.inc new file mode 100644 index 0000000..4b2a210 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.inc @@ -0,0 +1,13 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.php new file mode 100644 index 0000000..0f602d8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/GlobalKeywordUnitTest.php @@ -0,0 +1,56 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the GlobalKeyword sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\GlobalKeywordSniff + */ +class GlobalKeywordUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 8 => 1, + 9 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.1.inc new file mode 100644 index 0000000..d1863c0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.1.inc @@ -0,0 +1,12 @@ +foo. +Now, I am printing some {$foo->bar[1]}. +This should not print a capital 'A': \x41 +EOT; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.2.inc new file mode 100644 index 0000000..eb0062f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.2.inc @@ -0,0 +1,17 @@ + 'a' +<<<<<<< HEAD + 'b' => 'b' +======= + 'c' => 'c' +>>>>>>> master + ); + } diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.php new file mode 100644 index 0000000..de2d71e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/HeredocUnitTest.php @@ -0,0 +1,64 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the Heredoc sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\HeredocSniff + */ +class HeredocUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'HeredocUnitTest.1.inc': + return [ + 2 => 1, + 8 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/InnerFunctionsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/InnerFunctionsUnitTest.inc new file mode 100644 index 0000000..d16c7f2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/InnerFunctionsUnitTest.inc @@ -0,0 +1,87 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the InnerFunctions sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\InnerFunctionsSniff + */ +class InnerFunctionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 46 => 1, + 55 => 1, + 83 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc new file mode 100644 index 0000000..702b13d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc @@ -0,0 +1,50 @@ +Count(); +$count = $object::Count(); +$count = $object->count(); +$count = $object::count(); +class MyClass { + public function Count() {} +} + +function &Sort() { + +} + +$connection = new Db\Adapter\Pdo\Mysql($config); + +namespace Strtolower\Silly; + +use function strToUpper as somethingElse; +use function MyClass\WordsToUpper as UCWords; // Intentional redeclared function error. +use function strToUpper\NotTheFunction; + +class ArrayUnique {} + +$sillyComments = strToLower /*comment*/ ($string); + +$callToGlobalFunction = \STR_REPEAT($a, 2); +$callToGlobalFunction = \ /*comment*/ str_Repeat($a, 2); + +$callToNamespacedFunction = MyNamespace /* phpcs:ignore Standard */ \STR_REPEAT($a, 2); +$callToNamespacedFunction = namespace\STR_REPEAT($a, 2); // Could potentially be false negative. + +$filePath = new \File($path); + +$count = $object?->Count(); + +class AttributesShouldBeIgnored +{ + #[Putenv('FOO', 'foo')] + public function foo(): void + {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc.fixed new file mode 100644 index 0000000..281425c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.inc.fixed @@ -0,0 +1,50 @@ +Count(); +$count = $object::Count(); +$count = $object->count(); +$count = $object::count(); +class MyClass { + public function Count() {} +} + +function &Sort() { + +} + +$connection = new Db\Adapter\Pdo\Mysql($config); + +namespace Strtolower\Silly; + +use function strtoupper as somethingElse; +use function MyClass\WordsToUpper as UCWords; // Intentional redeclared function error. +use function strToUpper\NotTheFunction; + +class ArrayUnique {} + +$sillyComments = strtolower /*comment*/ ($string); + +$callToGlobalFunction = \str_repeat($a, 2); +$callToGlobalFunction = \ /*comment*/ str_repeat($a, 2); + +$callToNamespacedFunction = MyNamespace /* phpcs:ignore Standard */ \STR_REPEAT($a, 2); +$callToNamespacedFunction = namespace\STR_REPEAT($a, 2); // Could potentially be false negative. + +$filePath = new \File($path); + +$count = $object?->Count(); + +class AttributesShouldBeIgnored +{ + #[Putenv('FOO', 'foo')] + public function foo(): void + {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.php new file mode 100644 index 0000000..223496d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/LowercasePHPFunctionsUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LowercasePHPFunctions sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\LowercasePHPFunctionsSniff + */ +class LowercasePHPFunctionsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 4 => 1, + 27 => 1, + 33 => 1, + 35 => 1, + 36 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.1.inc new file mode 100644 index 0000000..4b1d1ca --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.1.inc @@ -0,0 +1,420 @@ +{$action . 'JsonAction'}(); +} + +switch (true) { + case 1: + return foo( + function () { + $foo = $bar; // when this is removed it works ok + return false; // from here on it reports unreachable + } + ); +} + +for($i=0,$j=50; $i<100; $i++) { + while($j--) { + if($j==17) { + goto end; + echo 'unreachable'; + } + } +} + +switch ($var) { + case '1': + goto end; + echo 'hi'; + + case '2': + case '3': + if ($something === true) { + goto end; + echo 'hi'; + } + break; + default: + goto end; + + if ($something === true) { + goto end; + echo 'hi'; + } +} + +end: +echo 'j hit 17'; + +// Issue 2512. +class TestAlternativeControlStructures { + + public function alternative_switch_in_function( $var ) { + + switch ( $var ) : + case 'value1': + do_something(); + break; + + default: + case 'value2': + do_something_else(); + break; + endswitch; + } + + public function various_alternative_control_structures() { + $_while = 1; + + for ( $a = 0; $a++ < 1; ) : + foreach ( [ 1 ] as $b ) : + while ( $_while-- ) : + if ( 1 ) : + switch ( 1 ) : + default: + echo 'yay, we made it!'; + break; + endswitch; + endif; + endwhile; + endforeach; + endfor; + } +} + +$var_after_class_in_global_space = 1; +do_something_else(); + +// These are parse errors, but that's not the concern of the sniff. +function parseError1() { + defined('FOO') or return 'foo'; + echo 'unreachable'; +} + +function parseError2() { + defined('FOO') || continue; + echo 'unreachable'; +} + +// All logical operators are allowed with inline expressions (but this was not correctly handled by the sniff). +function exitExpressionsWithLogicalOperators() { + $condition = false; + $condition || exit(); + $condition or die(); + + $condition = true; + $condition && die(); + $condition and exit; + + $condition xor die(); + + echo 'still executable as exit, in all of the above cases, is used as part of an expression'; +} + +// Inline expressions are allowed in ternaries. +function exitExpressionsInTernary() { + $value = $myValue ? $myValue : exit(); + $value = $myValue ?: exit(); + $value = $var == 'foo' ? 'bar' : die( 'world' ); + + $value = (!$myValue ) ? exit() : $myValue; + $value = $var != 'foo' ? die( 'world' ) : 'bar'; + + echo 'still executable'; +} + +// Inline expressions are allowed with null coalesce and null coalesce equals. +function exitExpressionsWithNullCoalesce() { + $value = $nullableValue ?? exit(); + $value ??= die(); + echo 'still executable'; +} + +// Inline expressions are allowed in arrow functions. +function exitExpressionsInArrowFunction() { + $callable = fn() => die(); + echo 'still executable'; +} + +// PHP 8.0+: throw expressions which don't stop execution. +function nonStoppingThrowExpressions() { + $callable = fn() => throw new Exception(); + + $value = $myValue ? 'something' : throw new Exception(); + $value = $myValue ?: throw new Exception(); + $value = $myValue ? throw new Exception() : 'something'; + + $value = $nullableValue ?? throw new Exception(); + $value ??= throw new Exception(); + + $condition && throw new Exception(); + $condition || throw new Exception(); + $condition and throw new Exception(); + $condition or throw new Exception(); + + echo 'still executable as throw, in all of the above cases, is used as part of an expression'; + + throw new Exception(); + echo 'non-executable'; +} + +// PHP 8.0+: throw expressions which do stop execution. +function executionStoppingThrowExpressionsA() { + $condition xor throw new Exception(); + echo 'non-executable'; +} + +function executionStoppingThrowExpressionsB() { + throw $userIsAuthorized ? new ForbiddenException() : new UnauthorizedException(); + echo 'non-executable'; +} + +function executionStoppingThrowExpressionsC() { + throw $condition1 && $condition2 ? new Exception1() : new Exception2(); + echo 'non-executable'; +} + +function executionStoppingThrowExpressionsD() { + throw $exception ??= new Exception(); + echo 'non-executable'; +} + +function executionStoppingThrowExpressionsE() { + throw $maybeNullException ?? new Exception(); + echo 'non-executable'; +} + +function returnNotRequiredIgnoreCommentsA() +{ + if ($something === TRUE) { + return /*comment*/; + } + + echo 'foo'; + return /*comment*/; +} + +function returnNotRequiredIgnoreCommentsB() +{ + echo 'foo'; + return; + /*comment*/ +} + +$closure = function () +{ + echo 'foo'; + return; // This return should be flagged as not required. +}; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.2.inc new file mode 100644 index 0000000..9b7a22b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.2.inc @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + +
    non-executable
    + + + + + + + + +
    non-executable
    + + + + + + + + +
    non-executable
    + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.4.inc new file mode 100644 index 0000000..189466b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.4.inc @@ -0,0 +1,6 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the NonExecutableCode sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\NonExecutableCodeSniff + */ +class NonExecutableCodeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getWarningList($testFile='') + { + switch ($testFile) { + case 'NonExecutableCodeUnitTest.1.inc': + return [ + 5 => 1, + 11 => 1, + 17 => 1, + 18 => 1, + 19 => 2, + 28 => 1, + 32 => 1, + 33 => 2, + 34 => 2, + 42 => 1, + 45 => 1, + 54 => 1, + 58 => 1, + 73 => 1, + 83 => 1, + 95 => 1, + 105 => 1, + 123 => 1, + 147 => 1, + 150 => 1, + 153 => 1, + 166 => 1, + 180 => 1, + 232 => 1, + 240 => 1, + 246 => 1, + 252 => 1, + 253 => 1, + 254 => 2, + 303 => 1, + 308 => 1, + 370 => 1, + 376 => 1, + 381 => 1, + 386 => 1, + 391 => 1, + 396 => 1, + 406 => 1, + 412 => 1, + 419 => 1, + ]; + + case 'NonExecutableCodeUnitTest.2.inc': + return [ + 7 => 1, + 8 => 1, + 9 => 1, + 10 => 2, + 14 => 1, + 54 => 2, + 65 => 2, + 69 => 2, + 70 => 2, + 71 => 2, + ]; + + case 'NonExecutableCodeUnitTest.3.inc': + return [ + 27 => 1, + 36 => 1, + 45 => 1, + 54 => 1, + 62 => 1, + ]; + default: + return []; + }//end switch + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MemberVarScopeUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MemberVarScopeUnitTest.inc new file mode 100644 index 0000000..6df12cc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MemberVarScopeUnitTest.inc @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Scope; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MemberVarScope sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MemberVarScopeSniff + */ +class MemberVarScopeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 25 => 1, + 29 => 1, + 33 => 1, + 39 => 1, + 41 => 1, + 66 => 2, + 67 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [71 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MethodScopeUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MethodScopeUnitTest.inc new file mode 100644 index 0000000..3cc617d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/MethodScopeUnitTest.inc @@ -0,0 +1,57 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Scope; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MethodScope sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff + */ +class MethodScopeUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 6 => 1, + 30 => 1, + 39 => 1, + 46 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.inc new file mode 100644 index 0000000..dd6530e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.inc @@ -0,0 +1,127 @@ +func2()); + $result = $this->getValue($value); + return $this->setValue($result); + } + + public static function /* */ func1() + { + return $this->setValue($result); + } + + public static function + func1() + { + return $this->setValue($result); + } + + public function func1() + { + $value = 'hello'; + $newValue = array($this->func2()); + $result = $this->getValue($value); + return $this->setValue($result); + } + + function func1() + { + $value = 'hello'; + $newValue = array($this->func2()); + $result = $this->getValue($value); + return $this->setValue($result); + } + + public static function func1() { + return function() { + echo $this->name; + }; + } + + private static function func1(array $data) + { + return new class() + { + private $data; + + public function __construct(array $data) + { + $this->data = $data; + } + }; + } + + public function getAnonymousClass() { + return new class() { + public static function something() { + $this->doSomething(); + } + }; + } +} + +trait MyTrait { + public static function myFunc() { + $this->doSomething(); + } +} + +$b = new class() +{ + public static function myFunc() { + $this->doSomething(); + } + + public static function other() { + return fn () => $this->name; + } + + public static function anonClassUseThis() { + return new class($this) { + public function __construct($class) { + } + }; + } + + public static function anonClassAnotherThis() { + return new class() { + public function __construct() { + $this->id = 1; + } + }; + } + + public static function anonClassNestedUseThis() { + return new class(new class($this) {}) { + }; + } + + public static function anonClassNestedAnotherThis() { + return new class(new class() { + public function __construct() { + $this->id = 1; + } + }) { + }; + } + + public static function thisMustBeLowercase() { + $This = 'hey'; + + return $This; + } +} + +enum MyEnum { + private function notStatic () { + $this->doSomething(); + } + + public static function myFunc() { + $this->doSomething(); + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.php new file mode 100644 index 0000000..9eee8c3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Scope/StaticThisUsageUnitTest.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Scope; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the StaticThisUsage sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\StaticThisUsageSniff + */ +class StaticThisUsageUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 7 => 1, + 8 => 1, + 9 => 1, + 14 => 1, + 20 => 1, + 41 => 1, + 61 => 1, + 69 => 1, + 76 => 1, + 80 => 1, + 84 => 1, + 99 => 1, + 125 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc new file mode 100644 index 0000000..3bf4186 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc @@ -0,0 +1,49 @@ +add_help_tab( array( +'id' => <<', +) ); + +// phpcs:set Squiz.Strings.ConcatenationSpacing spacing 1 + +$string = 'Hello'.$there.'. How are'.$you.$going. "today $okay"; +$string = 'Hello' . $there . '. How are' . $you . $going . "today $okay"; +$string = 'Hello'.$there; +$string = 'Hello'. $there; +$string = 'Hello' .$there; + +// phpcs:set Squiz.Strings.ConcatenationSpacing ignoreNewlines true +$y = '1' + . '2' + . '3'; + +$y = '1' . + '2' . + '3'; + +$y = '1' +. '2' +. '3'; + +$y = '1' + .'2'. + '3' + . '4'; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..b45f1a4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.inc.fixed @@ -0,0 +1,47 @@ +add_help_tab( array( +'id' => <<', +) ); + +// phpcs:set Squiz.Strings.ConcatenationSpacing spacing 1 + +$string = 'Hello' . $there . '. How are' . $you . $going . "today $okay"; +$string = 'Hello' . $there . '. How are' . $you . $going . "today $okay"; +$string = 'Hello' . $there; +$string = 'Hello' . $there; +$string = 'Hello' . $there; + +// phpcs:set Squiz.Strings.ConcatenationSpacing ignoreNewlines true +$y = '1' + . '2' + . '3'; + +$y = '1' . + '2' . + '3'; + +$y = '1' +. '2' +. '3'; + +$y = '1' + . '2' . + '3' + . '4'; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.php new file mode 100644 index 0000000..6d0181f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/ConcatenationSpacingUnitTest.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Strings; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ConcatenationSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\ConcatenationSpacingSniff + */ +class ConcatenationSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 5, + 5 => 1, + 6 => 1, + 9 => 1, + 10 => 1, + 12 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + 16 => 5, + 22 => 1, + 27 => 5, + 29 => 1, + 30 => 1, + 31 => 1, + 47 => 2, + 49 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc new file mode 100644 index 0000000..c8cc638 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc @@ -0,0 +1,37 @@ +"; +$string = "Value: $var[test]"; +$string = "\0"; +$string = "\$var"; + +$x = "bar = '$z', +baz = '" . $a . "'...$x"; + +$string = "Hello +there"; +$string = 'Hello +there'; + +$string = "\123 \234"."\u123"."\e"; + +echo "window.location = \"".$url."\";\n"; +echo "" + +$string = "Hello + there"; + +function test() { + echo "It Worked'; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc.fixed new file mode 100644 index 0000000..9730919 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.inc.fixed @@ -0,0 +1,37 @@ +"; +$string = "Value: $var[test]"; +$string = "\0"; +$string = '$var'; + +$x = "bar = '$z', +baz = '" . $a . "'...$x"; + +$string = 'Hello +there'; +$string = 'Hello +there'; + +$string = "\123 \234"."\u123"."\e"; + +echo 'window.location = "'.$url."\";\n"; +echo '' + +$string = 'Hello + there'; + +function test() { + echo "It Worked'; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.php new file mode 100644 index 0000000..e48dada --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/DoubleQuoteUsageUnitTest.php @@ -0,0 +1,67 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Strings; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the DoubleQuoteUsage sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\DoubleQuoteUsageSniff + */ +class DoubleQuoteUsageUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 5 => 1, + 6 => 1, + 8 => 2, + 14 => 1, + 15 => 1, + 17 => 1, + 19 => 1, + 20 => 1, + 22 => 1, + 29 => 1, + 30 => 1, + 32 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc new file mode 100644 index 0000000..9e0391d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc @@ -0,0 +1,13 @@ +returndate == 0) ? 'Not returned' : date('d/m/Y', $loan_device->returndate); +?> +

    +

    diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc.fixed new file mode 100644 index 0000000..37c7d24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.inc.fixed @@ -0,0 +1,13 @@ +returndate == 0) ? 'Not returned' : date('d/m/Y', $loan_device->returndate); +?> +

    +

    diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.php new file mode 100644 index 0000000..2722752 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/Strings/EchoedStringsUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\Strings; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the EchoedStrings sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\EchoedStringsSniff + */ +class EchoedStringsUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 5 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 9 => 1, + 13 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/CastSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/CastSpacingUnitTest.inc new file mode 100644 index 0000000..fa65112 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/CastSpacingUnitTest.inc @@ -0,0 +1,9 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the CastSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\CastSpacingSniff + */ +class CastSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 4 => 1, + 5 => 1, + 6 => 1, + 9 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc new file mode 100644 index 0000000..70abae4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc @@ -0,0 +1,269 @@ + +
    + + + +
    + children as $child) { + // There should be no error after this + // foreach, because it is followed by a + // close PHP tag. + } + ?> +
    +children as $child) { + echo $child; + +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +foreach ( $blah as $var ) { + if ( $blah ) { + } +} + +if ( + $defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +$moo = 'blar'; +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; + + default: + $moo = 'moo'; + break; +} + +do { +} +while (true); + +try { + // Something +} catch (Exception $e) { + // Something +} + +try { + + // Something + +} catch (Exception $e) { + + // Something + +} + +if ($one) { +} +elseif ($two) { +} +// else if something +else if ($three) { +} // else do something +else { +} + +if ($one) { + +} + +do { + echo 'hi'; +} while ( $blah ); + +if ($one) { +} +// No blank line here. +if ($two) { +} + +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + + return $moo; +} + +try { + // Something +} +catch (Exception $e) { + // Something +} +finally { + // Something +} + +if ($foo) { + + + /** + * Comment + */ + function foo() { + // Code here + } + + + /** + * Comment + */ + class bar() { + + }//end class + + +} + +if (true) { // some comment goes here + + echo 'foo'; +} + +if (true) { echo 'foo'; + + echo 'foo'; +} + +if ($true) { + echo 'hi 2'; +}//end if +echo 'hi'; + +if ($true) { + echo 'hi 2'; +} // phpcs:enable Standard.Category.Sniff -- for reasons. +echo 'hi'; + +?> + + + + + + + 1, + 2 => 2, + +}; +echo $expr; + +if($true) { + + enum SomeEnum {} + +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..c64de25 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.inc.fixed @@ -0,0 +1,261 @@ + + + + + +
    + children as $child) { + // There should be no error after this + // foreach, because it is followed by a + // close PHP tag. + } + ?> +
    +children as $child) { + echo $child; +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +foreach ($blah as $var) { + if ($blah) { + } +} + +if ($defaultPageDesign === 0 + && $defaultCascade === TRUE + && $defaultChildDesign === 0 +) { + $settingsUpdated = FALSE; +} + +$moo = 'blar'; +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; + + default: + $moo = 'moo'; + break; +} + +do { +} +while (true); + +try { + // Something +} catch (Exception $e) { + // Something +} + +try { + // Something +} catch (Exception $e) { + // Something +} + +if ($one) { +} +elseif ($two) { +} +// else if something +else if ($three) { +} // else do something +else { +} + +if ($one) { +} + +do { + echo 'hi'; +} while ($blah); + +if ($one) { +} + +// No blank line here. +if ($two) { +} + +switch ($moo) +{ + case 'blar': + if ($moo === 'blar2') { + $moo = 'blar' + } + return $moo; +} + +try { + // Something +} +catch (Exception $e) { + // Something +} +finally { + // Something +} + +if ($foo) { + + + /** + * Comment + */ + function foo() { + // Code here + } + + + /** + * Comment + */ + class bar() { + + }//end class + + +} + +if (true) { // some comment goes here + echo 'foo'; +} + +if (true) { echo 'foo'; + + echo 'foo'; +} + +if ($true) { + echo 'hi 2'; +}//end if + +echo 'hi'; + +if ($true) { + echo 'hi 2'; +} // phpcs:enable Standard.Category.Sniff -- for reasons. + +echo 'hi'; + +?> + + + + + + 1, + 2 => 2, +}; + +echo $expr; + +if($true) { + + enum SomeEnum {} + +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js new file mode 100644 index 0000000..1c889a1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js @@ -0,0 +1,93 @@ + +if (something) { +} +for (i = 0; i < 10; i++) { +} + +while (true) { + for (i = 0; i < 10; i++) { + } + if (something) { + } + + do { + } while (true); + +} + +if (one) { +} else (two) { +} else if (three) { +} +if (one) { +} else (two) { +} else if (three) { +} + +switch (blah) { + case 'one': + if (blah) { + // There are no spaces before break. + } + break; + + default: + if (blah) { + // There are no spaces before break. + } + break; +} + +switch (blah) { + case 'one': + if (blah) { + // There are no spaces before break. + } + break; + + default: + if (blah) { + // Code here. + } +} + +for (i = 0; i < 10; i++) { + if (blah) { + } + break; +} + +while (true) { + for (i = 0; i < 10; i++) { + + if (something) { + } + + } + + do { + + alert(i); + } while (true); +} + +for ( i = 0; i < 10; i++ ) { + if ( blah ) { + } +} + +var x = { + a: function () { + if (blah) { + } + + }, +}; + +if (one) { +} +// else if something +else if (two) { +} // else do something +else { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js.fixed new file mode 100644 index 0000000..bb979bc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.js.fixed @@ -0,0 +1,93 @@ + +if (something) { +} + +for (i = 0; i < 10; i++) { +} + +while (true) { + for (i = 0; i < 10; i++) { + } + + if (something) { + } + + do { + } while (true); +} + +if (one) { +} else (two) { +} else if (three) { +} + +if (one) { +} else (two) { +} else if (three) { +} + +switch (blah) { + case 'one': + if (blah) { + // There are no spaces before break. + } + break; + + default: + if (blah) { + // There are no spaces before break. + } + break; +} + +switch (blah) { + case 'one': + if (blah) { + // There are no spaces before break. + } + break; + + default: + if (blah) { + // Code here. + } +} + +for (i = 0; i < 10; i++) { + if (blah) { + } + + break; +} + +while (true) { + for (i = 0; i < 10; i++) { + if (something) { + } + } + + do { + alert(i); + } while (true); +} + +for (i = 0; i < 10; i++) { + if (blah) { + } +} + +var x = { + a: function () { + if (blah) { + } + + }, +}; + +if (one) { +} +// else if something +else if (two) { +} // else do something +else { +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php new file mode 100644 index 0000000..f3820bb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ControlStructureSpacingUnitTest.php @@ -0,0 +1,107 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ControlStructureSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff + */ +class ControlStructureSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ControlStructureSpacingUnitTest.inc': + return [ + 3 => 1, + 5 => 1, + 8 => 1, + 15 => 1, + 23 => 1, + 74 => 1, + 79 => 1, + 82 => 1, + 83 => 1, + 87 => 1, + 103 => 1, + 113 => 2, + 114 => 2, + 118 => 1, + 150 => 1, + 153 => 1, + 154 => 1, + 157 => 1, + 170 => 1, + 176 => 2, + 179 => 1, + 189 => 1, + 225 => 1, + 237 => 1, + 242 => 1, + 246 => 1, + 248 => 1, + 257 => 3, + 261 => 1, + 262 => 1, + ]; + + case 'ControlStructureSpacingUnitTest.js': + return [ + 3 => 1, + 9 => 1, + 15 => 1, + 21 => 1, + 56 => 1, + 61 => 1, + 64 => 1, + 65 => 1, + 68 => 1, + 74 => 2, + 75 => 2, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc new file mode 100644 index 0000000..e831e25 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionClosingBraceSpaceUnitTest.inc @@ -0,0 +1,39 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionClosingBraceSpace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionClosingBraceSpaceSniff + */ +class FunctionClosingBraceSpaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FunctionClosingBraceSpaceUnitTest.inc': + return [ + 10 => 1, + 21 => 1, + 28 => 1, + 29 => 1, + 31 => 1, + 39 => 1, + ]; + + case 'FunctionClosingBraceSpaceUnitTest.js': + return [ + 13 => 1, + 25 => 1, + 32 => 1, + 53 => 1, + 59 => 1, + 67 => 1, + 84 => 1, + 128 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionOpeningBraceSpaceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionOpeningBraceSpaceUnitTest.inc new file mode 100644 index 0000000..fe2c903 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionOpeningBraceSpaceUnitTest.inc @@ -0,0 +1,54 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionOpeningBraceSpace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionOpeningBraceSpaceSniff + */ +class FunctionOpeningBraceSpaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FunctionOpeningBraceSpaceUnitTest.inc': + return [ + 10 => 1, + 25 => 1, + 49 => 1, + ]; + + case 'FunctionOpeningBraceSpaceUnitTest.js': + return [ + 11 => 1, + 31 => 1, + 38 => 1, + 88 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionSpacingUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionSpacingUnitTest.1.inc new file mode 100644 index 0000000..b03a0ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/FunctionSpacingUnitTest.1.inc @@ -0,0 +1,584 @@ +setLogger(new class { + public function a(){} + private function b(){} + protected function c(){} +}); + +?> + +setLogger(new class { + + public function a(){} + + private function b(){} + + protected function c(){} + +}); + +?> + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the FunctionSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionSpacingSniff + */ +class FunctionSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'FunctionSpacingUnitTest.1.inc': + return [ + 26 => 1, + 35 => 1, + 44 => 1, + 51 => 1, + 55 => 1, + 61 => 1, + 64 => 1, + 66 => 1, + 81 => 1, + 100 => 1, + 111 => 1, + 113 => 1, + 119 => 2, + 141 => 1, + 160 => 1, + 173 => 2, + 190 => 1, + 224 => 2, + 281 => 1, + 282 => 1, + 295 => 1, + 297 => 1, + 303 => 1, + 327 => 1, + 329 => 1, + 338 => 1, + 344 => 1, + 345 => 1, + 354 => 2, + 355 => 1, + 356 => 1, + 360 => 2, + 361 => 1, + 362 => 1, + 385 => 1, + 399 => 1, + 411 => 2, + 418 => 2, + 426 => 2, + 432 => 1, + 437 => 1, + 438 => 1, + 442 => 2, + 444 => 1, + 449 => 1, + 458 => 2, + 459 => 1, + 460 => 1, + 465 => 2, + 466 => 1, + 467 => 1, + 471 => 1, + 473 => 2, + 475 => 1, + 478 => 2, + 479 => 1, + 483 => 2, + 495 => 1, + 529 => 1, + 539 => 1, + 547 => 2, + 551 => 1, + 553 => 1, + 560 => 1, + 566 => 1, + 580 => 2, + 583 => 3, + ]; + + case 'FunctionSpacingUnitTest.2.inc': + return [2 => 1]; + + case 'FunctionSpacingUnitTest.3.inc': + return [7 => 1]; + + case 'FunctionSpacingUnitTest.5.inc': + return [5 => 1]; + + case 'FunctionSpacingUnitTest.6.inc': + return [10 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.inc new file mode 100644 index 0000000..e8f2eda --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LanguageConstructSpacingUnitTest.inc @@ -0,0 +1,43 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LanguageConstructSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\LanguageConstructSpacingSniff + */ +class LanguageConstructSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 7 => 1, + 11 => 1, + 15 => 1, + 19 => 1, + 23 => 1, + 27 => 1, + 31 => 1, + 34 => 1, + 35 => 1, + 39 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LogicalOperatorSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LogicalOperatorSpacingUnitTest.inc new file mode 100644 index 0000000..c2f4ec7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/LogicalOperatorSpacingUnitTest.inc @@ -0,0 +1,19 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the LogicalOperatorSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\LogicalOperatorSpacingSniff + */ +class LogicalOperatorSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 2, + 5 => 3, + 6 => 3, + 15 => 1, + 17 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc new file mode 100644 index 0000000..12b5517 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc @@ -0,0 +1,374 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; +} + +// Make sure the determination of whether a property is the first property or not is done correctly. +class ClassUsingSimpleTraits +{ + use HelloWorld; + + + /* comment */ + public $firstVar = array( 'a', 'b' ); + protected $secondVar = true; +} + +class ClassUsingComplexTraits +{ + use A, B { + B::smallTalk insteadof A; + A::bigTalk insteadof B; + } + + + + public $firstVar = array( 'a', 'b' ); + + + /* comment */ + protected $secondVar = true; +} + +class Foo +{ + + + private function foo() + { + } + + + /* no error here because after function */ + private $bar = false; +} + +class CommentedOutCodeAtStartOfClass { + + /** + * Description. + * + * @var bool + */ + //public $commented_out_property = true; + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class CommentedOutCodeAtStartOfClassNoBlankLine { + + // phpcs:disable Stnd.Cat.Sniff -- For reasons. + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class HasAttributes +{ + /** + * Short description of the member variable. + * + * @var array + */ + + #[ORM\Id]#[ORM\Column("integer")] + + private $id; + + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; + + #[SingleAttribute] + protected $propertySingle; + + #[FirstAttribute] + #[SecondAttribute] + protected $propertyDouble; + #[ThirdAttribute] + protected $propertyWithoutSpacing; +} + +enum SomeEnum +{ + // Enum cannot have properties + + case ONE = 'one'; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..d683eaa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.inc.fixed @@ -0,0 +1,359 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; +} + +// Make sure the determination of whether a property is the first property or not is done correctly. +class ClassUsingSimpleTraits +{ + use HelloWorld; + + /* comment */ + public $firstVar = array( 'a', 'b' ); + + protected $secondVar = true; +} + +class ClassUsingComplexTraits +{ + use A, B { + B::smallTalk insteadof A; + A::bigTalk insteadof B; + } + + public $firstVar = array( 'a', 'b' ); + + /* comment */ + protected $secondVar = true; +} + +class Foo +{ + + + private function foo() + { + } + + + /* no error here because after function */ + private $bar = false; +} + +class CommentedOutCodeAtStartOfClass { + + /** + * Description. + * + * @var bool + */ + //public $commented_out_property = true; + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class CommentedOutCodeAtStartOfClassNoBlankLine { + + // phpcs:disable Stnd.Cat.Sniff -- For reasons. + + /** + * Description. + * + * @var bool + */ + public $property = true; +} + +class HasAttributes +{ + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\Id]#[ORM\Column("integer")] + private $id; + + /** + * Short description of the member variable. + * + * @var array + */ + #[ORM\GeneratedValue] + #[ORM\Column(ORM\Column::T_INTEGER)] + protected $height; + + #[SingleAttribute] + protected $propertySingle; + + #[FirstAttribute] + #[SecondAttribute] + protected $propertyDouble; + + #[ThirdAttribute] + protected $propertyWithoutSpacing; +} + +enum SomeEnum +{ + // Enum cannot have properties + + case ONE = 'one'; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.php new file mode 100644 index 0000000..fd3f77d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/MemberVarSpacingUnitTest.php @@ -0,0 +1,90 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the MemberVarSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\MemberVarSpacingSniff + */ +class MemberVarSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 4 => 1, + 7 => 1, + 20 => 1, + 30 => 1, + 35 => 1, + 44 => 1, + 50 => 1, + 73 => 1, + 86 => 1, + 106 => 1, + 115 => 1, + 150 => 1, + 160 => 1, + 165 => 1, + 177 => 1, + 186 => 1, + 200 => 1, + 209 => 1, + 211 => 1, + 224 => 1, + 229 => 1, + 241 => 1, + 246 => 1, + 252 => 1, + 254 => 1, + 261 => 1, + 275 => 1, + 276 => 1, + 288 => 1, + 292 => 1, + 333 => 1, + 342 => 1, + 346 => 1, + 353 => 1, + 357 => 1, + 366 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc new file mode 100644 index 0000000..67f8ee1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc @@ -0,0 +1,52 @@ +testThis(); +$this-> testThis(); +$this -> testThis(); +$this-> /* comment here */testThis(); +$this/* comment here */ -> testThis(); +$this + ->testThis(); +$this-> + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +$this->testThis(); +$this-> testThis(); +$this -> testThis(); +$this->/* comment here */testThis(); +$this/* comment here */ -> testThis(); +$this + ->testThis(); +$this-> + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +thisObject::testThis(); +thisObject:: testThis(); +thisObject :: testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */ :: testThis(); +thisObject + ::testThis(); +thisObject:: + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +thisObject::testThis(); +thisObject:: testThis(); +thisObject :: testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */ :: testThis(); +thisObject + ::testThis(); +thisObject:: + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +$this?->testThis(); +$this?-> testThis(); +$this ?-> testThis(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..730b8e4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed @@ -0,0 +1,48 @@ +testThis(); +$this->testThis(); +$this->testThis(); +$this->/* comment here */testThis(); +$this/* comment here */->testThis(); +$this->testThis(); +$this->testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +$this->testThis(); +$this->testThis(); +$this->testThis(); +$this->/* comment here */testThis(); +$this/* comment here */->testThis(); +$this + ->testThis(); +$this-> + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +thisObject::testThis(); +thisObject::testThis(); +thisObject::testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */::testThis(); +thisObject::testThis(); +thisObject::testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +thisObject::testThis(); +thisObject::testThis(); +thisObject::testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */::testThis(); +thisObject + ::testThis(); +thisObject:: + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +$this?->testThis(); +$this?->testThis(); +$this?->testThis(); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.php new file mode 100644 index 0000000..31f6a3f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ObjectOperatorSpacingUnitTest.php @@ -0,0 +1,73 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ObjectOperatorSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ObjectOperatorSpacingSniff + */ +class ObjectOperatorSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 4 => 2, + 5 => 1, + 6 => 2, + 8 => 1, + 9 => 1, + 15 => 1, + 16 => 2, + 18 => 2, + 27 => 1, + 28 => 2, + 30 => 2, + 32 => 1, + 33 => 1, + 39 => 1, + 40 => 2, + 42 => 2, + 51 => 1, + 52 => 2, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc new file mode 100644 index 0000000..765e7ab --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc @@ -0,0 +1,487 @@ + $j && $k< $l && $m>= $n && $o<= $p && $q<> $r; + +$a ==$b && $c !=$d && $e ===$f && $g !==$h; +$i >$j && $k <$l && $m >=$n && $o <=$p && $q <>$r; + +function myFunction($variable=0, $var2='string') {} + +if (index > -1) { +} + +array_walk_recursive($array, function(&$item) use (&$something) { +}); + +$var = saveFile(&$model, &$foo); + +// This is all valid. +$boo = -$foo; +function foo($boo = -1) {} +$foo = array('boo' => -1); +$x = $test ? -1 : 1; +$y = $test ? 1 : -1; +$z = $test ?: false; + +$closureWithDefaultParameter = function (array $testArray=array()) {}; + +switch ($foo) { + case -1: + break; +} + +$y = 1 * -1; +$y = -1 * 1; +$y = -1 * $var; +$y = 10 / -2; +$y = -10 / 2; +$y = (-10 / 2); +$y = (-10 / $var); +$y = 10 + -2; +$y = -10 + 2; + +$a = $x?$y:$z; +$a = $x ? $y : $z; + +$y = 1 + + 2 + - 3; + +$y = 1 + + 2 - + 3; + +$y = 1 ++ 2 +- 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$y = 1 + + 2 + - 3; + +$y = 1 + + 2 - + 3; + +$y = 1 ++ 2 +- 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == $b) { +} + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$y = array(&$x); +$y = [&$x]; +$y = array(&$a, &$b, &$c); +$y = [&$a, &$b, &$c]; +$y = array(&$a => 1, 2 => &$b, &$c); +$y = [&$a => 1, 2 => &$b, &$c]; + +if ($a <=> $b) { +} + +if ($a <=>$b) { +} + +$a |= $b; +$a **= $b; +$a ??= $b; + +$a = +1; + +function bar($boo = +1) {} + +$username = $_GET['user']??'nobody'; + +function foo(string $bar, array $baz, ?MyClass $object) : MyClass {} + +declare(strict_types=1); + +function foo($c = ((BAR)?10:100)) {} + +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; + +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; + +function foo(string $a = '', ?string $b = ''): ?string {} + +// Issue #1605. +$text = preg_replace_callback( + self::CHAR_REFS_REGEX, + [ 'Sanitizer', 'decodeCharReferencesCallback' ], + $text, /* limit */ -1, $count ); + +if (true || /* test */ -1 == $b) {} +$y = 10 + /* test */ -2; + +// Issue #1604. +Hooks::run( 'ParserOptionsRegister', [ + &self::$defaults, + &self::$inCacheKey, + &self::$lazyOptions, +] ); + +$x = $foo ? function (): int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) + // comment + : int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) use /* comment */ ($bar): int { + return 1; +} : $bar; + +$x = !$foo ? $bar : function (): int { + return 1; +}; + +$a = + // Comment. + [ + 'a', + 'b', + ]; + +$a = +// phpcs:ignore Standard.Category.Sniff -- for reasons. +[ + 'a', + 'b', +]; + +$foo = is_array($bar) ? array_map( + function () {}, + $bar + ) : $bar; + +function bar(): array {} + +if ($line{-1} === ':') { + $line = substr($line, 0, -1); +} + +$a = $a instanceof $b; +$a = $a instanceof $b; +$a = ($a)instanceof$b; + +fn&($x) => $x; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +$a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true +yield -1; +echo -1; +$a = -1; +func(-1); +$a = [-1]; +return -1; +print -1; +$a &= -1; +switch ($a) { + case -1: +} +$a = $a ?? -1; +$a .= -1; +$a /= -1; +$a = [1 => -1]; +$a = $a == -1; +$a = $a >= -1; +$a = $a === -1; +$a = $a != -1; +$a = $a !== -1; +$a = $a <= -1; +$a = $a <=> -1; +$a = $a and -1; +$a = $a or -1; +$a = $a xor -1; +$a -= -1; +$a %= -1; +$a *= -1; +$a |= -1; +$a += -1; +$a = $a ** -1; +$a **= -1; +$a = $a << -1; +$a <<= -1; +$a = $a >> -1; +$a >>= -1; +$a = (string) -1; +$a = (array) -1; +$a = (bool) -1; +$a = (object) -1; +$a = (unset) -1; +$a = (float) -1; +$a = (int) -1; +$a ^= -1; +$a = [$a, -1]; +$a = $a[-1]; +$a = $a ? -1 : -1; + +yield - 1; +echo - 1; +$a = - 1; +func(- 1); +$a = [- 1]; +return - 1; +print - 1; +$a &= - 1; +switch ($a) { + case - 1: +} +$a = $a ?? - 1; +$a .= - 1; +$a /= - 1; +$a = [1 => - 1]; +$a = $a == - 1; +$a = $a >= - 1; +$a = $a === - 1; +$a = $a != - 1; +$a = $a !== - 1; +$a = $a <= - 1; +$a = $a <=> - 1; +$a = $a and - 1; +$a = $a or - 1; +$a = $a xor - 1; +$a -= - 1; +$a %= - 1; +$a *= - 1; +$a |= - 1; +$a += - 1; +$a = $a ** - 1; +$a **= - 1; +$a = $a << - 1; +$a <<= - 1; +$a = $a >> - 1; +$a >>= - 1; +$a = (string) - 1; +$a = (array) - 1; +$a = (bool) - 1; +$a = (object) - 1; +$a = (unset) - 1; +$a = (float) - 1; +$a = (int) - 1; +$a ^= - 1; +$a = [$a, - 1]; +$a = $a[- 1]; +$a = $a ? - 1 : - 1; + + +yield -$b; +echo -$b; +$a = -$b; +func(-$b); +$a = [-$b]; +return -$b; +print -$b; +$a &= -$b; +switch ($a) { + case -$b: +} +$a = $a ?? -$b; +$a .= -$b; +$a /= -$b; +$a = [1 => -$b]; +$a = $a == -$b; +$a = $a >= -$b; +$a = $a === -$b; +$a = $a != -$b; +$a = $a !== -$b; +$a = $a <= -$b; +$a = $a <=> -$b; +$a = $a and -$b; +$a = $a or -$b; +$a = $a xor -$b; +$a -= -$b; +$a %= -$b; +$a *= -$b; +$a |= -$b; +$a += -$b; +$a = $a ** -$b; +$a **= -$b; +$a = $a << -$b; +$a <<= -$b; +$a = $a >> -$b; +$a >>= -$b; +$a = (string) -$b; +$a = (array) -$b; +$a = (bool) -$b; +$a = (object) -$b; +$a = (unset) -$b; +$a = (float) -$b; +$a = (int) -$b; +$a ^= -$b; +$a = [$a, -$b]; +$a = $a[-$b]; +$a = $a ? -$b : -$b; + +yield - $b; +echo - $b; +$a = - $b; +func(- $b); +$a = [- $b]; +return - $b; +print - $b; +$a &= - $b; +switch ($a) { + case - $b: +} +$a = $a ?? - $b; +$a .= - $b; +$a /= - $b; +$a = [1 => - $b]; +$a = $a == - $b; +$a = $a >= - $b; +$a = $a === - $b; +$a = $a != - $b; +$a = $a !== - $b; +$a = $a <= - $b; +$a = $a <=> - $b; +$a = $a and - $b; +$a = $a or - $b; +$a = $a xor - $b; +$a -= - $b; +$a %= - $b; +$a *= - $b; +$a |= - $b; +$a += - $b; +$a = $a ** - $b; +$a **= - $b; +$a = $a << - $b; +$a <<= - $b; +$a = $a >> - $b; +$a >>= - $b; +$a = (string) - $b; +$a = (array) - $b; +$a = (bool) - $b; +$a = (object) - $b; +$a = (unset) - $b; +$a = (float) - $b; +$a = (int) - $b; +$a ^= - $b; +$a = [$a, - $b]; +$a = $a[- $b]; +$a = $a ? - $b : - $b; + +exit -1; + +$cl = function ($boo =-1) {}; +$cl = function ($boo =+1) {}; +$fn = fn ($boo =-1) => $boo; +$fn = fn ($boo =+1) => $boo; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +$a = 'a '.-MY_CONSTANT; +$a = 'a '.-$b; +$a = 'a '.- MY_CONSTANT; +$a = 'a '.- $b; + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +/* Intentional parse error. This has to be the last test in the file. */ +$a = 10 + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..ada77fa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed @@ -0,0 +1,481 @@ + $j && $k < $l && $m >= $n && $o <= $p && $q <> $r; + +$a == $b && $c != $d && $e === $f && $g !== $h; +$i > $j && $k < $l && $m >= $n && $o <= $p && $q <> $r; + +function myFunction($variable=0, $var2='string') {} + +if (index > -1) { +} + +array_walk_recursive($array, function(&$item) use (&$something) { +}); + +$var = saveFile(&$model, &$foo); + +// This is all valid. +$boo = -$foo; +function foo($boo = -1) {} +$foo = array('boo' => -1); +$x = $test ? -1 : 1; +$y = $test ? 1 : -1; +$z = $test ?: false; + +$closureWithDefaultParameter = function (array $testArray=array()) {}; + +switch ($foo) { + case -1: + break; +} + +$y = 1 * -1; +$y = -1 * 1; +$y = -1 * $var; +$y = 10 / -2; +$y = -10 / 2; +$y = (-10 / 2); +$y = (-10 / $var); +$y = 10 + -2; +$y = -10 + 2; + +$a = $x ? $y : $z; +$a = $x ? $y : $z; + +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; + +$y = 1 + 2 - 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +$y = 1 + + 2 + - 3; + +$y = 1 + + 2 - + 3; + +$y = 1 ++ 2 +- 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == $b) { +} + +$var = array(-1); +$var = [-1]; +$var = [0, -1, -2]; + +$y = array(&$x); +$y = [&$x]; +$y = array(&$a, &$b, &$c); +$y = [&$a, &$b, &$c]; +$y = array(&$a => 1, 2 => &$b, &$c); +$y = [&$a => 1, 2 => &$b, &$c]; + +if ($a <=> $b) { +} + +if ($a <=> $b) { +} + +$a |= $b; +$a **= $b; +$a ??= $b; + +$a = +1; + +function bar($boo = +1) {} + +$username = $_GET['user'] ?? 'nobody'; + +function foo(string $bar, array $baz, ?MyClass $object) : MyClass {} + +declare(strict_types=1); + +function foo($c = ((BAR) ? 10 : 100)) {} + +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; +$res = $a ?: $b; + +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; +$res = $a ? : $b; + +function foo(string $a = '', ?string $b = ''): ?string {} + +// Issue #1605. +$text = preg_replace_callback( + self::CHAR_REFS_REGEX, + [ 'Sanitizer', 'decodeCharReferencesCallback' ], + $text, /* limit */ -1, $count ); + +if (true || /* test */ -1 == $b) {} +$y = 10 + /* test */ -2; + +// Issue #1604. +Hooks::run( 'ParserOptionsRegister', [ + &self::$defaults, + &self::$inCacheKey, + &self::$lazyOptions, +] ); + +$x = $foo ? function (): int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) + // comment + : int { + return 1; +} : $bar; + +$x = $foo ? function ($foo) use /* comment */ ($bar): int { + return 1; +} : $bar; + +$x = !$foo ? $bar : function (): int { + return 1; +}; + +$a = + // Comment. + [ + 'a', + 'b', + ]; + +$a = +// phpcs:ignore Standard.Category.Sniff -- for reasons. +[ + 'a', + 'b', +]; + +$foo = is_array($bar) ? array_map( + function () {}, + $bar + ) : $bar; + +function bar(): array {} + +if ($line{-1} === ':') { + $line = substr($line, 0, -1); +} + +$a = $a instanceof $b; +$a = $a instanceof $b; +$a = ($a) instanceof $b; + +fn&($x) => $x; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +$a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true +yield -1; +echo -1; +$a = -1; +func(-1); +$a = [-1]; +return -1; +print -1; +$a &= -1; +switch ($a) { + case -1: +} +$a = $a ?? -1; +$a .= -1; +$a /= -1; +$a = [1 => -1]; +$a = $a == -1; +$a = $a >= -1; +$a = $a === -1; +$a = $a != -1; +$a = $a !== -1; +$a = $a <= -1; +$a = $a <=> -1; +$a = $a and -1; +$a = $a or -1; +$a = $a xor -1; +$a -= -1; +$a %= -1; +$a *= -1; +$a |= -1; +$a += -1; +$a = $a ** -1; +$a **= -1; +$a = $a << -1; +$a <<= -1; +$a = $a >> -1; +$a >>= -1; +$a = (string) -1; +$a = (array) -1; +$a = (bool) -1; +$a = (object) -1; +$a = (unset) -1; +$a = (float) -1; +$a = (int) -1; +$a ^= -1; +$a = [$a, -1]; +$a = $a[-1]; +$a = $a ? -1 : -1; + +yield - 1; +echo - 1; +$a = - 1; +func(- 1); +$a = [- 1]; +return - 1; +print - 1; +$a &= - 1; +switch ($a) { + case - 1: +} +$a = $a ?? - 1; +$a .= - 1; +$a /= - 1; +$a = [1 => - 1]; +$a = $a == - 1; +$a = $a >= - 1; +$a = $a === - 1; +$a = $a != - 1; +$a = $a !== - 1; +$a = $a <= - 1; +$a = $a <=> - 1; +$a = $a and - 1; +$a = $a or - 1; +$a = $a xor - 1; +$a -= - 1; +$a %= - 1; +$a *= - 1; +$a |= - 1; +$a += - 1; +$a = $a ** - 1; +$a **= - 1; +$a = $a << - 1; +$a <<= - 1; +$a = $a >> - 1; +$a >>= - 1; +$a = (string) - 1; +$a = (array) - 1; +$a = (bool) - 1; +$a = (object) - 1; +$a = (unset) - 1; +$a = (float) - 1; +$a = (int) - 1; +$a ^= - 1; +$a = [$a, - 1]; +$a = $a[- 1]; +$a = $a ? - 1 : - 1; + + +yield -$b; +echo -$b; +$a = -$b; +func(-$b); +$a = [-$b]; +return -$b; +print -$b; +$a &= -$b; +switch ($a) { + case -$b: +} +$a = $a ?? -$b; +$a .= -$b; +$a /= -$b; +$a = [1 => -$b]; +$a = $a == -$b; +$a = $a >= -$b; +$a = $a === -$b; +$a = $a != -$b; +$a = $a !== -$b; +$a = $a <= -$b; +$a = $a <=> -$b; +$a = $a and -$b; +$a = $a or -$b; +$a = $a xor -$b; +$a -= -$b; +$a %= -$b; +$a *= -$b; +$a |= -$b; +$a += -$b; +$a = $a ** -$b; +$a **= -$b; +$a = $a << -$b; +$a <<= -$b; +$a = $a >> -$b; +$a >>= -$b; +$a = (string) -$b; +$a = (array) -$b; +$a = (bool) -$b; +$a = (object) -$b; +$a = (unset) -$b; +$a = (float) -$b; +$a = (int) -$b; +$a ^= -$b; +$a = [$a, -$b]; +$a = $a[-$b]; +$a = $a ? -$b : -$b; + +yield - $b; +echo - $b; +$a = - $b; +func(- $b); +$a = [- $b]; +return - $b; +print - $b; +$a &= - $b; +switch ($a) { + case - $b: +} +$a = $a ?? - $b; +$a .= - $b; +$a /= - $b; +$a = [1 => - $b]; +$a = $a == - $b; +$a = $a >= - $b; +$a = $a === - $b; +$a = $a != - $b; +$a = $a !== - $b; +$a = $a <= - $b; +$a = $a <=> - $b; +$a = $a and - $b; +$a = $a or - $b; +$a = $a xor - $b; +$a -= - $b; +$a %= - $b; +$a *= - $b; +$a |= - $b; +$a += - $b; +$a = $a ** - $b; +$a **= - $b; +$a = $a << - $b; +$a <<= - $b; +$a = $a >> - $b; +$a >>= - $b; +$a = (string) - $b; +$a = (array) - $b; +$a = (bool) - $b; +$a = (object) - $b; +$a = (unset) - $b; +$a = (float) - $b; +$a = (int) - $b; +$a ^= - $b; +$a = [$a, - $b]; +$a = $a[- $b]; +$a = $a ? - $b : - $b; + +exit -1; + +$cl = function ($boo =-1) {}; +$cl = function ($boo =+1) {}; +$fn = fn ($boo =-1) => $boo; +$fn = fn ($boo =+1) => $boo; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +$a = 'a '.-MY_CONSTANT; +$a = 'a '.-$b; +$a = 'a '.- MY_CONSTANT; +$a = 'a '.- $b; + +match ($a) { + 'a' => -1, + 'b', 'c', 'd' => -2, + default => -3, +}; + +/* Intentional parse error. This has to be the last test in the file. */ +$a = 10 + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js new file mode 100644 index 0000000..f37df9d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js @@ -0,0 +1,104 @@ + + +result = 1 + 2; +result = 1 + 2; +result = 1 + 2; +result = 1 +2; +result = 1+ 2; +result = 1+2; + +result = 1 - 2; +result = 1 - 2; +result = 1 - 2; +result = 1 -2; +result = 1- 2; +result = 1-2; + +result = 1 * 2; +result = 1 * 2; +result = 1 * 2; +result = 1 *2; +result = 1* 2; +result = 1*2; + +result = 1 / 2; +result = 1 / 2; +result = 1 / 2; +result = 1 /2; +result = 1/ 2; +result = 1/2; + +result = 1 % 2; +result = 1 % 2; +result = 1 % 2; +result = 1 %2; +result = 1% 2; +result = 1%2; +result = '100%'; + +result += 4; +result+=4; +result -= 4; +result-=4; +result /= 4; +result/=4; +result *=4; +result*=4; + +$.localScroll({offset: {top: -32}}); + +switch (result) { + case -1: + break; +} + +result = x?y:z; +result = x ? y : z; + +if (something === true + ^ somethingElse === true +) { + return false; +} + +y = 1 + + 2 + - 3; + +y = 1 + + 2 - + 3; + +y = 1 ++ 2 +- 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +y = 1 + + 2 + - 3; + +y = 1 + + 2 - + 3; + +y = 1 ++ 2 +- 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == b) { +} + +x = x << y; +x <<= y; +x = x >> y; +x >>= y; +x = x >>> y; +x >>>= y; + +var foo = bar.map(baz=> baz.length); + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed new file mode 100644 index 0000000..47c8930 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed @@ -0,0 +1,98 @@ + + +result = 1 + 2; +result = 1 + 2; +result = 1 + 2; +result = 1 + 2; +result = 1 + 2; +result = 1 + 2; + +result = 1 - 2; +result = 1 - 2; +result = 1 - 2; +result = 1 - 2; +result = 1 - 2; +result = 1 - 2; + +result = 1 * 2; +result = 1 * 2; +result = 1 * 2; +result = 1 * 2; +result = 1 * 2; +result = 1 * 2; + +result = 1 / 2; +result = 1 / 2; +result = 1 / 2; +result = 1 / 2; +result = 1 / 2; +result = 1 / 2; + +result = 1 % 2; +result = 1 % 2; +result = 1 % 2; +result = 1 % 2; +result = 1 % 2; +result = 1 % 2; +result = '100%'; + +result += 4; +result += 4; +result -= 4; +result -= 4; +result /= 4; +result /= 4; +result *= 4; +result *= 4; + +$.localScroll({offset: {top: -32}}); + +switch (result) { + case -1: + break; +} + +result = x ? y : z; +result = x ? y : z; + +if (something === true + ^ somethingElse === true +) { + return false; +} + +y = 1 + 2 - 3; + +y = 1 + 2 - 3; + +y = 1 + 2 - 3; + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines true +y = 1 + + 2 + - 3; + +y = 1 + + 2 - + 3; + +y = 1 ++ 2 +- 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreNewlines false + +if (true || -1 == b) { +} + +x = x << y; +x <<= y; +x = x >> y; +x >>= y; +x = x >>> y; +x >>>= y; + +var foo = bar.map(baz => baz.length); + +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments false +a = 3; +// phpcs:set Squiz.WhiteSpace.OperatorSpacing ignoreSpacingBeforeAssignments true diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php new file mode 100644 index 0000000..66b780a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php @@ -0,0 +1,174 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the OperatorSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff + */ +class OperatorSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'OperatorSpacingUnitTest.inc': + return [ + 4 => 1, + 5 => 2, + 6 => 1, + 7 => 1, + 8 => 2, + 11 => 1, + 12 => 2, + 13 => 1, + 14 => 1, + 15 => 2, + 18 => 1, + 19 => 2, + 20 => 1, + 21 => 1, + 22 => 2, + 25 => 1, + 26 => 2, + 27 => 1, + 28 => 1, + 29 => 2, + 32 => 1, + 33 => 2, + 34 => 1, + 35 => 1, + 36 => 2, + 40 => 2, + 42 => 2, + 44 => 2, + 45 => 1, + 46 => 2, + 53 => 4, + 54 => 3, + 59 => 10, + 64 => 1, + 77 => 4, + 78 => 1, + 79 => 1, + 80 => 2, + 81 => 1, + 84 => 6, + 85 => 6, + 87 => 4, + 88 => 5, + 90 => 4, + 91 => 5, + 128 => 4, + 132 => 1, + 133 => 1, + 135 => 1, + 136 => 1, + 140 => 1, + 141 => 1, + 174 => 1, + 177 => 1, + 178 => 1, + 179 => 1, + 185 => 2, + 191 => 4, + 194 => 1, + 195 => 1, + 196 => 2, + 199 => 1, + 200 => 1, + 201 => 2, + 239 => 1, + 246 => 1, + 265 => 2, + 266 => 2, + 271 => 2, + ]; + + case 'OperatorSpacingUnitTest.js': + return [ + 4 => 1, + 5 => 2, + 6 => 1, + 7 => 1, + 8 => 2, + 11 => 1, + 12 => 2, + 13 => 1, + 14 => 1, + 15 => 2, + 18 => 1, + 19 => 2, + 20 => 1, + 21 => 1, + 22 => 2, + 25 => 1, + 26 => 2, + 27 => 1, + 28 => 1, + 29 => 2, + 32 => 1, + 33 => 2, + 34 => 1, + 35 => 1, + 36 => 2, + 40 => 2, + 42 => 2, + 44 => 2, + 45 => 1, + 46 => 2, + 55 => 4, + 65 => 1, + 66 => 1, + 68 => 1, + 69 => 1, + 73 => 1, + 74 => 1, + 100 => 1, + 103 => 2, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js new file mode 100644 index 0000000..15890b9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js @@ -0,0 +1,40 @@ +var x = { + b: 'x', + xasd: x, + abc:x, + a: function () { + alert('thats right'); + x = (x?a:x); + }, + casdasd : 123123, + omgwtfbbq: { + a: 1, + b: 2 + } +}; + +id = id.replace(/row\/:/gi, ''); + +outer_loop: +for (i=0; i<3; i++) { + for (j=0; j<5; j++) { + if (j==x) + break outer_loop; + } +} +alert('hi'); + +even_number: if ((i % 2) == 0) { + if (i == 12) + break even_number; +} + +switch (blah) { + case dfx.DOM_VK_LEFT: + this.caretLeft(shiftKey); + break; + default: + if (blah) { + } + break; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js.fixed new file mode 100644 index 0000000..f332878 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.js.fixed @@ -0,0 +1,39 @@ +var x = { + b: 'x', + xasd: x, + abc: x, + a: function () { + alert('thats right'); + x = (x?a:x); + }, + casdasd: 123123, + omgwtfbbq: { + a: 1, + b: 2 + } +}; + +id = id.replace(/row\/:/gi, ''); + +outer_loop: for (i=0; i<3; i++) { + for (j=0; j<5; j++) { + if (j==x) + break outer_loop; + } +} +alert('hi'); + +even_number: if ((i % 2) == 0) { + if (i == 12) + break even_number; +} + +switch (blah) { + case dfx.DOM_VK_LEFT: + this.caretLeft(shiftKey); + break; + default: + if (blah) { + } + break; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.php new file mode 100644 index 0000000..32561da --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/PropertyLabelSpacingUnitTest.php @@ -0,0 +1,60 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the PropertyLabel sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\PropertyLabelSpacingSniff + */ +class PropertyLabelSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 2 => 1, + 4 => 1, + 9 => 2, + 10 => 1, + 12 => 1, + 18 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc new file mode 100644 index 0000000..ecae5c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeClosingBraceUnitTest.inc @@ -0,0 +1,134 @@ +{$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +if ($token['code'] === T_COMMENT + && $multiLineComment === false + && (substr($token['content'], 0, 2) === '//' + || $token['content']{0} === '#') +) { +} + +switch ($blah) { + case 'one': + echo 'one'; + break; + default: + echo 'another'; +} + +?> + +getRow()): ?> +

    + + + +
    + +

    o hai!

    + +
    + + + + + + + + + + + + $x + $y; + +$match = match ($test) { 1 => 'a', 2 => 'b' }; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' + }; + +?> + +
    + +
    + +{$property} =& new $class_name($this->db_index); + $this->modules[$module] =& $this->{$property}; +} + +foreach ($elements as $element) { + if ($something) { + // Do IF. + } else if ($somethingElse) { + // Do ELSE. + } +} + +if ($token['code'] === T_COMMENT + && $multiLineComment === false + && (substr($token['content'], 0, 2) === '//' + || $token['content']{0} === '#') +) { +} + +switch ($blah) { + case 'one': + echo 'one'; + break; + default: + echo 'another'; +} + +?> + +getRow()): ?> +

    + + + +
    + +

    o hai!

    + +
    + + + + + + + + + + + + $x + $y; + +$match = match ($test) { 1 => 'a', 2 => 'b' +}; + +$match = match ($test) { + 1 => 'a', + 2 => 'b' +}; + +?> + +
    + +
    + + + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ScopeClosingBrace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff + */ +class ScopeClosingBraceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 11 => 1, + 13 => 1, + 24 => 1, + 80 => 1, + 102 => 1, + 111 => 1, + 116 => 1, + 122 => 1, + 130 => 1, + 134 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc new file mode 100644 index 0000000..a76f42f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc @@ -0,0 +1,141 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; + + // Intentionally missing a semi-colon for testing. + public + $varS, + $varT +} + +// Issue #3188 - static as return type. +public static function fCreate($attributes = []): static +{ + return static::factory()->create($attributes); +} + +public static function fCreate($attributes = []): ?static +{ + return static::factory()->create($attributes); +} + +// Also account for static used within union types. +public function staticLast($attributes = []): object|static {} +public function staticMiddle(): string|static|object {} +public function staticFirst(): static|object {} + +// Ensure that static as a scope keyword when preceeded by a colon which is not for a type declaration is still handled. +$callback = $cond ? get_fn_name() : static function ($a) { return $a * 10; }; + +class TypedProperties { + public + int $var; + + protected string $stringA, $stringB; + + private bool + $boolA, + $boolB; +} + +// PHP 8.0 constructor property promotion. +class ConstructorPropertyPromotionTest { + public function __construct( + public $x = 0.0, + protected $y = '', + private $z = null, + $normalParam, + ) {} +} + +class ConstructorPropertyPromotionWithTypesTest { + public function __construct(protected float|int $x, public?string &$y = 'test', private mixed $z) {} +} + +// PHP 8.1 readonly keywords. +class ReadonlyTest { + public readonly int $publicReadonlyProperty; + + protected readonly int $protectedReadonlyProperty; + + readonly protected int $protectedReadonlyProperty; + + readonly private int $privateReadonlyProperty; + + public function __construct(readonly protected float|int $x, public readonly?string &$y = 'test') {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000..7fd8062 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.1.inc.fixed @@ -0,0 +1,135 @@ + 'a', 'b' => 'b' ), + $varQ = 'string', + $varR = 123; + + // Intentionally missing a semi-colon for testing. + public + $varS, + $varT +} + +// Issue #3188 - static as return type. +public static function fCreate($attributes = []): static +{ + return static::factory()->create($attributes); +} + +public static function fCreate($attributes = []): ?static +{ + return static::factory()->create($attributes); +} + +// Also account for static used within union types. +public function staticLast($attributes = []): object|static {} +public function staticMiddle(): string|static|object {} +public function staticFirst(): static|object {} + +// Ensure that static as a scope keyword when preceeded by a colon which is not for a type declaration is still handled. +$callback = $cond ? get_fn_name() : static function ($a) { return $a * 10; }; + +class TypedProperties { + public int $var; + + protected string $stringA, $stringB; + + private bool + $boolA, + $boolB; +} + +// PHP 8.0 constructor property promotion. +class ConstructorPropertyPromotionTest { + public function __construct( + public $x = 0.0, + protected $y = '', + private $z = null, + $normalParam, + ) {} +} + +class ConstructorPropertyPromotionWithTypesTest { + public function __construct(protected float|int $x, public ?string &$y = 'test', private mixed $z) {} +} + +// PHP 8.1 readonly keywords. +class ReadonlyTest { + public readonly int $publicReadonlyProperty; + + protected readonly int $protectedReadonlyProperty; + + readonly protected int $protectedReadonlyProperty; + + readonly private int $privateReadonlyProperty; + + public function __construct(readonly protected float|int $x, public readonly ?string &$y = 'test') {} +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc new file mode 100644 index 0000000..45cfb53 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/ScopeKeywordSpacingUnitTest.2.inc @@ -0,0 +1,6 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ScopeKeywordSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeKeywordSpacingSniff + */ +class ScopeKeywordSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ScopeKeywordSpacingUnitTest.1.inc': + return [ + 7 => 2, + 8 => 1, + 13 => 1, + 14 => 1, + 15 => 1, + 17 => 2, + 26 => 1, + 28 => 1, + 29 => 1, + 64 => 1, + 67 => 1, + 71 => 1, + 103 => 1, + 106 => 1, + 111 => 1, + 119 => 1, + 121 => 1, + 127 => 2, + 134 => 2, + 138 => 2, + 140 => 3, + ]; + + case 'ScopeKeywordSpacingUnitTest.3.inc': + return [6 => 1]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc new file mode 100644 index 0000000..393f484 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc @@ -0,0 +1,42 @@ +testThis(); +$test = $this->testThis() ; +$test = $this->testThis() ; +for ($var = 1 ; $var < 10 ; $var++) { + echo $var ; +} +$test = $this->testThis() /* comment here */; +$test = $this->testThis() /* comment here */ ; + +$hello ='foo'; +; + +$sum = $a /* + $b */; +$sum = $a // + $b +; +$sum = $a /* + $b + + $c */ ; + +/* + * Test that the sniff does *not* throw incorrect errors for semi-colons in + * "empty" parts of a `for` control structure. + */ +for ($i = 1; ; $i++) {} +for ( ; $ptr >= 0; $ptr-- ) {} +for ( ; ; ) {} + +// But it should when the semi-colon in a `for` follows a comment (but shouldn't move the semi-colon). +for ( /* Deliberately left empty. */ ; $ptr >= 0; $ptr-- ) {} +for ( $i = 1 ; /* Deliberately left empty. */ ; $i++ ) {} + +switch ($foo) { + case 'foo': + ; + break + ; +} + +// This is an empty statement and should be ignored. +if ($foo) { +; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc.fixed new file mode 100644 index 0000000..0d06324 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.inc.fixed @@ -0,0 +1,41 @@ +testThis(); +$test = $this->testThis(); +$test = $this->testThis(); +for ($var = 1; $var < 10; $var++) { + echo $var; +} +$test = $this->testThis(); /* comment here */ +$test = $this->testThis(); /* comment here */ + +$hello ='foo'; +; + +$sum = $a; /* + $b */ +$sum = $a; // + $b + +$sum = $a; /* + $b + + $c */ + +/* + * Test that the sniff does *not* throw incorrect errors for semi-colons in + * "empty" parts of a `for` control structure. + */ +for ($i = 1; ; $i++) {} +for ( ; $ptr >= 0; $ptr-- ) {} +for ( ; ; ) {} + +// But it should when the semi-colon in a `for` follows a comment (but shouldn't move the semi-colon). +for ( /* Deliberately left empty. */; $ptr >= 0; $ptr-- ) {} +for ( $i = 1; /* Deliberately left empty. */; $i++ ) {} + +switch ($foo) { + case 'foo': + ; + break; +} + +// This is an empty statement and should be ignored. +if ($foo) { +; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js new file mode 100644 index 0000000..3aafd6d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js @@ -0,0 +1,25 @@ +var x = { + a: function () { + alert('thats right') ; + x = (x?a:x) ; + }, +} ; + +id = id.replace(/row\/:;/gi, ''); + +for (i=0 ; i<3 ; i++) { + for (j=0; j<5 ; j++) { + if (j==x) + break ; + } +} +alert('hi'); +; + +var sum = a /* + b */; + +var sum = a // +b +; + +var sum = a /* +b + + c */ ; diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js.fixed new file mode 100644 index 0000000..a547144 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.js.fixed @@ -0,0 +1,25 @@ +var x = { + a: function () { + alert('thats right'); + x = (x?a:x); + }, +}; + +id = id.replace(/row\/:;/gi, ''); + +for (i=0; i<3; i++) { + for (j=0; j<5; j++) { + if (j==x) + break; + } +} +alert('hi'); +; + +var sum = a; /* + b */ + +var sum = a; // +b + + +var sum = a; /* +b + + c */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.php new file mode 100644 index 0000000..2f31ffb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SemicolonSpacingUnitTest.php @@ -0,0 +1,87 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SemicolonSpacing sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\SemicolonSpacingSniff + */ +class SemicolonSpacingUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'SemicolonSpacingUnitTest.inc': + return [ + 3 => 1, + 4 => 1, + 5 => 2, + 6 => 1, + 8 => 1, + 9 => 1, + 14 => 1, + 16 => 1, + 18 => 1, + 29 => 1, + 30 => 2, + 36 => 1, + ]; + + case 'SemicolonSpacingUnitTest.js': + return [ + 3 => 1, + 4 => 1, + 6 => 1, + 10 => 2, + 11 => 1, + 13 => 1, + 19 => 1, + 22 => 1, + 25 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css new file mode 100644 index 0000000..e3f3f02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css @@ -0,0 +1,32 @@ + +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} + +.HelpWidgetType-new-bug-title{ + float: left; +} + +/* phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines true */ +.HelpWidgetType-new-bug-title{ + float: left; +} + +.HelpWidgetType-new-bug-title{ + float: left; +} +/* phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines false */ + +// /** +// * This text is in two types of comment: each line is commented out +// * individually, and the whole block is in what looks like a +// * docblock-comment. This sniff should ignore all this text as there +// * is no superfluous white-space here. +// */ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css.fixed new file mode 100644 index 0000000..11be21d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.css.fixed @@ -0,0 +1,30 @@ +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} +.HelpWidgetType-new-bug-title { + float: left; +} + +.HelpWidgetType-new-bug-title{ + float: left; +} + +/* phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines true */ +.HelpWidgetType-new-bug-title{ + float: left; +} + +.HelpWidgetType-new-bug-title{ + float: left; +} +/* phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines false */ + +// /** +// * This text is in two types of comment: each line is commented out +// * individually, and the whole block is in what looks like a +// * docblock-comment. This sniff should ignore all this text as there +// * is no superfluous white-space here. +// */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc new file mode 100644 index 0000000..f9dca29 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc @@ -0,0 +1,74 @@ + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc.fixed new file mode 100644 index 0000000..1d764eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.inc.fixed @@ -0,0 +1,68 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js new file mode 100644 index 0000000..be542e7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js @@ -0,0 +1,56 @@ + +alert('hi'); +alert('hello'); + +if (something) { + +} + + +function myFunction() +{ + alert('code here'); + + alert('code here'); + + + // Hello. + + /* + HI + */ + + +} + +function myFunction2() +{ + alert('code here'); + + + alert('code here'); + +} + +MyFunction = function() +{ + alert('code here'); + + + alert('code here'); + +}; + +// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines true + +function myFunction2() +{ + alert('code here'); + + alert('code here'); + +} + +// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines false + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js.fixed new file mode 100644 index 0000000..960111a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.1.js.fixed @@ -0,0 +1,50 @@ +alert('hi'); +alert('hello'); + +if (something) { + +} + + +function myFunction() +{ + alert('code here'); + + alert('code here'); + + // Hello. + + /* + HI + */ + +} + +function myFunction2() +{ + alert('code here'); + + alert('code here'); + +} + +MyFunction = function() +{ + alert('code here'); + + alert('code here'); + +}; + +// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines true + +function myFunction2() +{ + alert('code here'); + + alert('code here'); + +} + +// phpcs:set Squiz.WhiteSpace.SuperfluousWhitespace ignoreBlankLines false + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css new file mode 100644 index 0000000..2025eeb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css @@ -0,0 +1,3 @@ +.HelpWidgetType-new-bug-title { + float: left; +} \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css.fixed new file mode 100644 index 0000000..2025eeb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.css.fixed @@ -0,0 +1,3 @@ +.HelpWidgetType-new-bug-title { + float: left; +} \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc new file mode 100644 index 0000000..a6e2b8a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc @@ -0,0 +1,9 @@ + + +

    + +

    + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc.fixed new file mode 100644 index 0000000..78c4525 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.inc.fixed @@ -0,0 +1,7 @@ + +

    + +

    diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js new file mode 100644 index 0000000..7b0c8ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js @@ -0,0 +1 @@ +alert('hi'); \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js.fixed new file mode 100644 index 0000000..7b0c8ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.2.js.fixed @@ -0,0 +1 @@ +alert('hi'); \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css new file mode 100644 index 0000000..9f794a0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css @@ -0,0 +1,3 @@ +.HelpWidgetType-new-bug-title { + float: left; +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css.fixed new file mode 100644 index 0000000..2025eeb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.css.fixed @@ -0,0 +1,3 @@ +.HelpWidgetType-new-bug-title { + float: left; +} \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc new file mode 100644 index 0000000..661ebda --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc.fixed new file mode 100644 index 0000000..0cb9748 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.inc.fixed @@ -0,0 +1,5 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js new file mode 100644 index 0000000..70f6719 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js @@ -0,0 +1 @@ +alert('hi'); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js.fixed new file mode 100644 index 0000000..70f6719 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.3.js.fixed @@ -0,0 +1 @@ +alert('hi'); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc new file mode 100644 index 0000000..96860ff --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc.fixed new file mode 100644 index 0000000..b26b5b2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.4.inc.fixed @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc new file mode 100644 index 0000000..4d6f06b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc @@ -0,0 +1,5 @@ +   +  \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc.fixed new file mode 100644 index 0000000..8ec5f30 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.5.inc.fixed @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.php new file mode 100644 index 0000000..7064de2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests/WhiteSpace/SuperfluousWhitespaceUnitTest.php @@ -0,0 +1,117 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Squiz\Tests\WhiteSpace; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the SuperfluousWhitespace sniff. + * + * @covers \PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\SuperfluousWhitespaceSniff + */ +class SuperfluousWhitespaceUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'SuperfluousWhitespaceUnitTest.1.inc': + return [ + 2 => 1, + 4 => 1, + 5 => 1, + 6 => 1, + 7 => 1, + 16 => 1, + 23 => 1, + 28 => 1, + 33 => 1, + 49 => 1, + 62 => 1, + 65 => 1, + 73 => 1, + ]; + + case 'SuperfluousWhitespaceUnitTest.2.inc': + return [ + 2 => 1, + 8 => 1, + ]; + + case 'SuperfluousWhitespaceUnitTest.3.inc': + return [ + 6 => 1, + 10 => 1, + ]; + + case 'SuperfluousWhitespaceUnitTest.4.inc': + case 'SuperfluousWhitespaceUnitTest.5.inc': + return [ + 1 => 1, + 4 => 1, + ]; + + case 'SuperfluousWhitespaceUnitTest.1.js': + return [ + 1 => 1, + 3 => 1, + 4 => 1, + 5 => 1, + 6 => 1, + 15 => 1, + 22 => 1, + 29 => 1, + 38 => 1, + 56 => 1, + ]; + + case 'SuperfluousWhitespaceUnitTest.1.css': + return [ + 1 => 1, + 8 => 1, + 9 => 1, + 11 => 1, + 32 => 1, + ]; + + default: + return []; + }//end switch + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/ruleset.xml new file mode 100644 index 0000000..87ab4c3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Squiz/ruleset.xml @@ -0,0 +1,132 @@ + + + The Squiz coding standard. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + %2$s + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + + + + + + 0 + + + error + + + + + 0 + + + error + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Debug/CodeAnalyzerStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Debug/CodeAnalyzerStandard.xml new file mode 100644 index 0000000..c462b4f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Debug/CodeAnalyzerStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $bar + $baz; +} + ]]> + + + $bar + 2; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Files/ClosingTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Files/ClosingTagStandard.xml new file mode 100644 index 0000000..aa60b8a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Files/ClosingTagStandard.xml @@ -0,0 +1,22 @@ + + + + + + + + + + ?> + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/NamingConventions/ValidVariableNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/NamingConventions/ValidVariableNameStandard.xml new file mode 100644 index 0000000..5bcde4b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/NamingConventions/ValidVariableNameStandard.xml @@ -0,0 +1,37 @@ + + + + + + + $testNumber = 1; + ]]> + + + $Test_Number = 1; + ]]> + + + + + _bar; +} + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Debug/CodeAnalyzerSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Debug/CodeAnalyzerSniff.php new file mode 100644 index 0000000..ffbab02 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Debug/CodeAnalyzerSniff.php @@ -0,0 +1,98 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Sniffs\Debug; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Util\Common; + +class CodeAnalyzerSniff implements Sniff +{ + + + /** + * Returns the token types that this sniff is interested in. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return int + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If ZendCodeAnalyzer could not be run. + */ + public function process(File $phpcsFile, $stackPtr) + { + $analyzerPath = Config::getExecutablePath('zend_ca'); + if ($analyzerPath === null) { + return ($phpcsFile->numTokens + 1); + } + + $fileName = $phpcsFile->getFilename(); + + // In the command, 2>&1 is important because the code analyzer sends its + // findings to stderr. $output normally contains only stdout, so using 2>&1 + // will pipe even stderr to stdout. + $cmd = Common::escapeshellcmd($analyzerPath).' '.escapeshellarg($fileName).' 2>&1'; + + // There is the possibility to pass "--ide" as an option to the analyzer. + // This would result in an output format which would be easier to parse. + // The problem here is that no cleartext error messages are returned; only + // error-code-labels. So for a start we go for cleartext output. + $exitCode = exec($cmd, $output, $retval); + + // Variable $exitCode is the last line of $output if no error occurs, on + // error it is numeric. Try to handle various error conditions and + // provide useful error reporting. + if (is_numeric($exitCode) === true && $exitCode > 0) { + if (is_array($output) === true) { + $msg = join('\n', $output); + } + + throw new RuntimeException("Failed invoking ZendCodeAnalyzer, exitcode was [$exitCode], retval was [$retval], output was [$msg]"); + } + + if (is_array($output) === true) { + foreach ($output as $finding) { + // The first two lines of analyzer output contain + // something like this: + // > Zend Code Analyzer 1.2.2 + // > Analyzing ... + // So skip these... + $res = preg_match("/^.+\(line ([0-9]+)\):(.+)$/", $finding, $regs); + if (empty($regs) === true || $res === false) { + continue; + } + + $phpcsFile->addWarningOnLine(trim($regs[2]), $regs[1], 'ExternalTool'); + } + } + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Files/ClosingTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Files/ClosingTagSniff.php new file mode 100644 index 0000000..5ae7236 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Files/ClosingTagSniff.php @@ -0,0 +1,79 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Sniffs\Files; + +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class ClosingTagSniff implements Sniff +{ + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [T_OPEN_TAG]; + + }//end register() + + + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + // Find the last non-empty token. + $tokens = $phpcsFile->getTokens(); + for ($last = ($phpcsFile->numTokens - 1); $last > 0; $last--) { + if (trim($tokens[$last]['content']) !== '') { + break; + } + } + + if ($tokens[$last]['code'] === T_CLOSE_TAG) { + $error = 'A closing tag is not permitted at the end of a PHP file'; + $fix = $phpcsFile->addFixableError($error, $last, 'NotAllowed'); + if ($fix === true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($last, $phpcsFile->eolChar); + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($last - 1), null, true); + if ($tokens[$prev]['code'] !== T_SEMICOLON + && $tokens[$prev]['code'] !== T_CLOSE_CURLY_BRACKET + && $tokens[$prev]['code'] !== T_OPEN_TAG + ) { + $phpcsFile->fixer->addContent($prev, ';'); + } + + $phpcsFile->fixer->endChangeset(); + } + + $phpcsFile->recordMetric($stackPtr, 'PHP closing tag at EOF', 'yes'); + } else { + $phpcsFile->recordMetric($stackPtr, 'PHP closing tag at EOF', 'no'); + }//end if + + // Ignore the rest of the file. + return ($phpcsFile->numTokens + 1); + + }//end process() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/NamingConventions/ValidVariableNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/NamingConventions/ValidVariableNameSniff.php new file mode 100644 index 0000000..2dfeb39 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/NamingConventions/ValidVariableNameSniff.php @@ -0,0 +1,196 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Sniffs\AbstractVariableSniff; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; + +class ValidVariableNameSniff extends AbstractVariableSniff +{ + + + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processVariable(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $varName = ltrim($tokens[$stackPtr]['content'], '$'); + + // If it's a php reserved var, then its ok. + if (isset($this->phpReservedVars[$varName]) === true) { + return; + } + + $objOperator = $phpcsFile->findNext([T_WHITESPACE], ($stackPtr + 1), null, true); + if ($tokens[$objOperator]['code'] === T_OBJECT_OPERATOR + || $tokens[$objOperator]['code'] === T_NULLSAFE_OBJECT_OPERATOR + ) { + // Check to see if we are using a variable from an object. + $var = $phpcsFile->findNext([T_WHITESPACE], ($objOperator + 1), null, true); + if ($tokens[$var]['code'] === T_STRING) { + // Either a var name or a function call, so check for bracket. + $bracket = $phpcsFile->findNext([T_WHITESPACE], ($var + 1), null, true); + + if ($tokens[$bracket]['code'] !== T_OPEN_PARENTHESIS) { + $objVarName = $tokens[$var]['content']; + + // There is no way for us to know if the var is public or private, + // so we have to ignore a leading underscore if there is one and just + // check the main part of the variable name. + $originalVarName = $objVarName; + if (substr($objVarName, 0, 1) === '_') { + $objVarName = substr($objVarName, 1); + } + + if (Common::isCamelCaps($objVarName, false, true, false) === false) { + $error = 'Variable "%s" is not in valid camel caps format'; + $data = [$originalVarName]; + $phpcsFile->addError($error, $var, 'NotCamelCaps', $data); + } else if (preg_match('|\d|', $objVarName) === 1) { + $warning = 'Variable "%s" contains numbers but this is discouraged'; + $data = [$originalVarName]; + $phpcsFile->addWarning($warning, $stackPtr, 'ContainsNumbers', $data); + } + }//end if + }//end if + }//end if + + // There is no way for us to know if the var is public or private, + // so we have to ignore a leading underscore if there is one and just + // check the main part of the variable name. + $originalVarName = $varName; + if (substr($varName, 0, 1) === '_') { + $objOperator = $phpcsFile->findPrevious([T_WHITESPACE], ($stackPtr - 1), null, true); + if ($tokens[$objOperator]['code'] === T_DOUBLE_COLON) { + // The variable lives within a class, and is referenced like + // this: MyClass::$_variable, so we don't know its scope. + $inClass = true; + } else { + $inClass = $phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens); + } + + if ($inClass === true) { + $varName = substr($varName, 1); + } + } + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Variable "%s" is not in valid camel caps format'; + $data = [$originalVarName]; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); + } else if (preg_match('|\d|', $varName) === 1) { + $warning = 'Variable "%s" contains numbers but this is discouraged'; + $data = [$originalVarName]; + $phpcsFile->addWarning($warning, $stackPtr, 'ContainsNumbers', $data); + } + + }//end processVariable() + + + /** + * Processes class member variables. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + protected function processMemberVar(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $varName = ltrim($tokens[$stackPtr]['content'], '$'); + $memberProps = $phpcsFile->getMemberProperties($stackPtr); + if (empty($memberProps) === true) { + // Exception encountered. + return; + } + + $public = ($memberProps['scope'] === 'public'); + + if ($public === true) { + if (substr($varName, 0, 1) === '_') { + $error = 'Public member variable "%s" must not contain a leading underscore'; + $data = [$varName]; + $phpcsFile->addError($error, $stackPtr, 'PublicHasUnderscore', $data); + } + } else { + if (substr($varName, 0, 1) !== '_') { + $scope = ucfirst($memberProps['scope']); + $error = '%s member variable "%s" must contain a leading underscore'; + $data = [ + $scope, + $varName, + ]; + $phpcsFile->addError($error, $stackPtr, 'PrivateNoUnderscore', $data); + } + } + + // Remove a potential underscore prefix for testing CamelCaps. + $varName = ltrim($varName, '_'); + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Member variable "%s" is not in valid camel caps format'; + $data = [$varName]; + $phpcsFile->addError($error, $stackPtr, 'MemberVarNotCamelCaps', $data); + } else if (preg_match('|\d|', $varName) === 1) { + $warning = 'Member variable "%s" contains numbers but this is discouraged'; + $data = [$varName]; + $phpcsFile->addWarning($warning, $stackPtr, 'MemberVarContainsNumbers', $data); + } + + }//end processMemberVar() + + + /** + * Processes the variable found within a double quoted string. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the double quoted + * string. + * + * @return void + */ + protected function processVariableInString(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + + if (preg_match_all('|[^\\\]\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[$stackPtr]['content'], $matches) !== 0) { + foreach ($matches[1] as $varName) { + // If it's a php reserved var, then its ok. + if (isset($this->phpReservedVars[$varName]) === true) { + continue; + } + + if (Common::isCamelCaps($varName, false, true, false) === false) { + $error = 'Variable "%s" is not in valid camel caps format'; + $data = [$varName]; + $phpcsFile->addError($error, $stackPtr, 'StringVarNotCamelCaps', $data); + } else if (preg_match('|\d|', $varName) === 1) { + $warning = 'Variable "%s" contains numbers but this is discouraged'; + $data = [$varName]; + $phpcsFile->addWarning($warning, $stackPtr, 'StringVarContainsNumbers', $data); + } + }//end foreach + }//end if + + }//end processVariableInString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.inc new file mode 100644 index 0000000..c8d0499 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.inc @@ -0,0 +1,6 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.php new file mode 100644 index 0000000..ec0e849 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Debug/CodeAnalyzerUnitTest.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Tests\Debug; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; +use PHP_CodeSniffer\Config; + +/** + * Unit test class for the CodeAnalyzer sniff. + * + * @covers \PHP_CodeSniffer\Standards\Zend\Sniffs\Debug\CodeAnalyzerSniff + */ +class CodeAnalyzerUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Should this test be skipped for some reason. + * + * @return bool + */ + protected function shouldSkipTest() + { + $analyzerPath = Config::getExecutablePath('zend_ca'); + if ($analyzerPath === null) { + return true; + } + + return false; + + }//end shouldSkipTest() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return []; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [2 => 1]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc new file mode 100644 index 0000000..7e7089d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc @@ -0,0 +1,12 @@ + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc.fixed new file mode 100644 index 0000000..caf3b38 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.1.inc.fixed @@ -0,0 +1,12 @@ + + +

    + +
    diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc new file mode 100644 index 0000000..63df04d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc @@ -0,0 +1 @@ +add('arg'))?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc.fixed new file mode 100644 index 0000000..b4c4621 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.3.inc.fixed @@ -0,0 +1 @@ +add('arg')); diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc new file mode 100644 index 0000000..539365d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc @@ -0,0 +1 @@ +add('arg')) /* comment */ ?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc.fixed new file mode 100644 index 0000000..4cc31a5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.4.inc.fixed @@ -0,0 +1 @@ +add('arg')); /* comment */ diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc new file mode 100644 index 0000000..09e4844 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc @@ -0,0 +1 @@ +add('arg')); } ?> diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc.fixed new file mode 100644 index 0000000..9ff112a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.5.inc.fixed @@ -0,0 +1 @@ +add('arg')); } diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc new file mode 100644 index 0000000..48de7e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc.fixed new file mode 100644 index 0000000..796727a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.6.inc.fixed @@ -0,0 +1,3 @@ + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.7.inc.fixed b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.7.inc.fixed new file mode 100644 index 0000000..dc84e23 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/Files/ClosingTagUnitTest.7.inc.fixed @@ -0,0 +1 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Tests\Files; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ClosingTag sniff. + * + * @covers \PHP_CodeSniffer\Standards\Zend\Sniffs\Files\ClosingTagSniff + */ +class ClosingTagUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @param string $testFile The name of the file being tested. + * + * @return array + */ + public function getErrorList($testFile='') + { + switch ($testFile) { + case 'ClosingTagUnitTest.1.inc': + return [11 => 1]; + + case 'ClosingTagUnitTest.3.inc': + case 'ClosingTagUnitTest.4.inc': + case 'ClosingTagUnitTest.5.inc': + case 'ClosingTagUnitTest.7.inc': + return [1 => 1]; + + case 'ClosingTagUnitTest.6.inc': + return [3 => 1]; + + default: + return []; + } + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return []; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.inc b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.inc new file mode 100644 index 0000000..3325e11 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.inc @@ -0,0 +1,131 @@ +varName; +echo $this->var_name; +echo $this->varname; +echo $this->_varName; +echo $this->varName2; +echo $object->varName; +echo $object->var_name; +echo $object->varName2; +echo $object_name->varname; +echo $object_name->_varName; +echo $object_name->varName2; + +echo $this->myFunction($one, $two); +echo $object->myFunction($one_two, $var2); + +$error = "format is \$GLOBALS['$varName']"; +$error = "format is \$GLOBALS['$varName2']"; + +echo $_SESSION['var_name']; +echo $_FILES['var_name']; +echo $_ENV['var_name']; +echo $_COOKIE['var_name']; +echo $_COOKIE['var_name2']; + +$XML = 'hello'; +$myXML = 'hello'; +$XMLParser = 'hello'; +$xmlParser = 'hello'; +$xmlParser2 = 'hello'; + +echo "{$_SERVER['HOSTNAME']} $var_name"; + +$someObject->{$name}; +$someObject->my_function($var_name); + +var_dump($http_response_header); +var_dump($HTTP_RAW_POST_DATA); +var_dump($php_errormsg); + +interface Base +{ + protected $anonymous; + + public function __construct(); +} + +$anonClass = new class() { + public function foo($foo, $_foo, $foo_bar) { + $bar = 1; + $_bar = 2; + $bar_foo = 3; + } +}; + +echo $obj?->varName; +echo $obj?->var_name; +echo $obj?->varName; + +enum SomeEnum +{ + public function foo($foo, $_foo, $foo_bar) { + $bar = 1; + $_bar = 2; + $bar_foo = 3; + } +} diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.php b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.php new file mode 100644 index 0000000..1df307e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests/NamingConventions/ValidVariableNameUnitTest.php @@ -0,0 +1,101 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Standards\Zend\Tests\NamingConventions; + +use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; + +/** + * Unit test class for the ValidVariableName sniff. + * + * @covers \PHP_CodeSniffer\Standards\Zend\Sniffs\NamingConventions\ValidVariableNameSniff + */ +class ValidVariableNameUnitTest extends AbstractSniffUnitTest +{ + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + public function getErrorList() + { + return [ + 3 => 1, + 5 => 1, + 11 => 1, + 13 => 1, + 17 => 1, + 19 => 1, + 23 => 1, + 25 => 1, + 29 => 1, + 31 => 1, + 36 => 1, + 38 => 1, + 42 => 1, + 44 => 1, + 48 => 1, + 50 => 1, + 61 => 1, + 67 => 1, + 72 => 1, + 74 => 1, + 75 => 1, + 76 => 1, + 79 => 1, + 96 => 1, + 99 => 1, + 113 => 1, + 116 => 1, + 121 => 1, + 126 => 1, + 129 => 1, + ]; + + }//end getErrorList() + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + public function getWarningList() + { + return [ + 6 => 1, + 14 => 1, + 20 => 1, + 26 => 1, + 32 => 1, + 39 => 1, + 45 => 1, + 51 => 1, + 64 => 1, + 70 => 1, + 73 => 1, + 76 => 1, + 79 => 1, + 82 => 1, + 94 => 1, + 107 => 1, + ]; + + }//end getWarningList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Zend/ruleset.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/ruleset.xml new file mode 100644 index 0000000..d10b103 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Zend/ruleset.xml @@ -0,0 +1,32 @@ + + + A coding standard based on an early Zend Framework coding standard. Note that this standard is out of date. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Tokenizers/CSS.php b/vendor/squizlabs/php_codesniffer/src/Tokenizers/CSS.php new file mode 100644 index 0000000..d3f71b3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Tokenizers/CSS.php @@ -0,0 +1,541 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tokenizers; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\TokenizerException; +use PHP_CodeSniffer\Util; + +class CSS extends PHP +{ + + + /** + * Initialise the tokenizer. + * + * Pre-checks the content to see if it looks minified. + * + * @param string $content The content to tokenize, + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param string $eolChar The EOL char used in the content. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\TokenizerException If the file appears to be minified. + */ + public function __construct($content, Config $config, $eolChar='\n') + { + if ($this->isMinifiedContent($content, $eolChar) === true) { + throw new TokenizerException('File appears to be minified and cannot be processed'); + } + + parent::__construct($content, $config, $eolChar); + + }//end __construct() + + + /** + * Creates an array of tokens when given some CSS code. + * + * Uses the PHP tokenizer to do all the tricky work + * + * @param string $string The string to tokenize. + * + * @return array + */ + public function tokenize($string) + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START CSS TOKENIZING 1ST PASS ***".PHP_EOL; + } + + // If the content doesn't have an EOL char on the end, add one so + // the open and close tags we add are parsed correctly. + $eolAdded = false; + if (substr($string, (strlen($this->eolChar) * -1)) !== $this->eolChar) { + $string .= $this->eolChar; + $eolAdded = true; + } + + $string = str_replace('', '^PHPCS_CSS_T_CLOSE_TAG^', $string); + $tokens = parent::tokenize(''); + + $finalTokens = []; + $finalTokens[0] = [ + 'code' => T_OPEN_TAG, + 'type' => 'T_OPEN_TAG', + 'content' => '', + ]; + + $newStackPtr = 1; + $numTokens = count($tokens); + $multiLineComment = false; + for ($stackPtr = 1; $stackPtr < $numTokens; $stackPtr++) { + $token = $tokens[$stackPtr]; + + // CSS files don't have lists, breaks etc, so convert these to + // standard strings early so they can be converted into T_STYLE + // tokens and joined with other strings if needed. + if ($token['code'] === T_BREAK + || $token['code'] === T_LIST + || $token['code'] === T_DEFAULT + || $token['code'] === T_SWITCH + || $token['code'] === T_FOR + || $token['code'] === T_FOREACH + || $token['code'] === T_WHILE + || $token['code'] === T_DEC + || $token['code'] === T_NEW + ) { + $token['type'] = 'T_STRING'; + $token['code'] = T_STRING; + } + + $token['content'] = str_replace('^PHPCS_CSS_T_OPEN_TAG^', '', $token['content']); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $token['type']; + $content = Util\Common::prepareForOutput($token['content']); + echo "\tProcess token $stackPtr: $type => $content".PHP_EOL; + } + + if ($token['code'] === T_BITWISE_XOR + && $tokens[($stackPtr + 1)]['content'] === 'PHPCS_CSS_T_OPEN_TAG' + ) { + $content = ''; + $stackPtr += 2; + break; + } else { + $content .= $tokens[$stackPtr]['content']; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> Found embedded PHP code: "; + $cleanContent = Util\Common::prepareForOutput($content); + echo $cleanContent.PHP_EOL; + } + + $finalTokens[$newStackPtr] = [ + 'type' => 'T_EMBEDDED_PHP', + 'code' => T_EMBEDDED_PHP, + 'content' => $content, + ]; + + $newStackPtr++; + continue; + }//end if + + if ($token['code'] === T_GOTO_LABEL) { + // Convert these back to T_STRING followed by T_COLON so we can + // more easily process style definitions. + $finalTokens[$newStackPtr] = [ + 'type' => 'T_STRING', + 'code' => T_STRING, + 'content' => substr($token['content'], 0, -1), + ]; + $newStackPtr++; + $finalTokens[$newStackPtr] = [ + 'type' => 'T_COLON', + 'code' => T_COLON, + 'content' => ':', + ]; + $newStackPtr++; + continue; + } + + if ($token['code'] === T_FUNCTION) { + // There are no functions in CSS, so convert this to a string. + $finalTokens[$newStackPtr] = [ + 'type' => 'T_STRING', + 'code' => T_STRING, + 'content' => $token['content'], + ]; + + $newStackPtr++; + continue; + } + + if ($token['code'] === T_COMMENT + && substr($token['content'], 0, 2) === '/*' + ) { + // Multi-line comment. Record it so we can ignore other + // comment tags until we get out of this one. + $multiLineComment = true; + } + + if ($token['code'] === T_COMMENT + && $multiLineComment === false + && (substr($token['content'], 0, 2) === '//' + || $token['content'][0] === '#') + ) { + $content = ltrim($token['content'], '#/'); + + // Guard against PHP7+ syntax errors by stripping + // leading zeros so the content doesn't look like an invalid int. + $leadingZero = false; + if ($content[0] === '0') { + $content = '1'.$content; + $leadingZero = true; + } + + $commentTokens = parent::tokenize(''); + + // The first and last tokens are the open/close tags. + array_shift($commentTokens); + $closeTag = array_pop($commentTokens); + + while ($closeTag['content'] !== '?'.'>') { + $closeTag = array_pop($commentTokens); + } + + if ($leadingZero === true) { + $commentTokens[0]['content'] = substr($commentTokens[0]['content'], 1); + $content = substr($content, 1); + } + + if ($token['content'][0] === '#') { + // The # character is not a comment in CSS files, so + // determine what it means in this context. + $firstContent = $commentTokens[0]['content']; + + // If the first content is just a number, it is probably a + // colour like 8FB7DB, which PHP splits into 8 and FB7DB. + if (($commentTokens[0]['code'] === T_LNUMBER + || $commentTokens[0]['code'] === T_DNUMBER) + && $commentTokens[1]['code'] === T_STRING + ) { + $firstContent .= $commentTokens[1]['content']; + array_shift($commentTokens); + } + + // If the first content looks like a colour and not a class + // definition, join the tokens together. + if (preg_match('/^[ABCDEF0-9]+$/i', $firstContent) === 1 + && $commentTokens[1]['content'] !== '-' + ) { + array_shift($commentTokens); + // Work out what we trimmed off above and remember to re-add it. + $trimmed = substr($token['content'], 0, (strlen($token['content']) - strlen($content))); + $finalTokens[$newStackPtr] = [ + 'type' => 'T_COLOUR', + 'code' => T_COLOUR, + 'content' => $trimmed.$firstContent, + ]; + } else { + $finalTokens[$newStackPtr] = [ + 'type' => 'T_HASH', + 'code' => T_HASH, + 'content' => '#', + ]; + } + } else { + $finalTokens[$newStackPtr] = [ + 'type' => 'T_STRING', + 'code' => T_STRING, + 'content' => '//', + ]; + }//end if + + $newStackPtr++; + + array_splice($tokens, $stackPtr, 1, $commentTokens); + $numTokens = count($tokens); + $stackPtr--; + continue; + }//end if + + if ($token['code'] === T_COMMENT + && substr($token['content'], -2) === '*/' + ) { + // Multi-line comment is done. + $multiLineComment = false; + } + + $finalTokens[$newStackPtr] = $token; + $newStackPtr++; + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END CSS TOKENIZING 1ST PASS ***".PHP_EOL; + echo "\t*** START CSS TOKENIZING 2ND PASS ***".PHP_EOL; + } + + // A flag to indicate if we are inside a style definition, + // which is defined using curly braces. + $inStyleDef = false; + + // A flag to indicate if an At-rule like "@media" is used, which will result + // in nested curly brackets. + $asperandStart = false; + + $numTokens = count($finalTokens); + for ($stackPtr = 0; $stackPtr < $numTokens; $stackPtr++) { + $token = $finalTokens[$stackPtr]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $token['type']; + $content = Util\Common::prepareForOutput($token['content']); + echo "\tProcess token $stackPtr: $type => $content".PHP_EOL; + } + + switch ($token['code']) { + case T_OPEN_CURLY_BRACKET: + // Opening curly brackets for an At-rule do not start a style + // definition. We also reset the asperand flag here because the next + // opening curly bracket could be indeed the start of a style + // definition. + if ($asperandStart === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if ($inStyleDef === true) { + echo "\t\t* style definition closed *".PHP_EOL; + } + + if ($asperandStart === true) { + echo "\t\t* at-rule definition closed *".PHP_EOL; + } + } + + $inStyleDef = false; + $asperandStart = false; + } else { + $inStyleDef = true; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* style definition opened *".PHP_EOL; + } + } + break; + case T_CLOSE_CURLY_BRACKET: + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if ($inStyleDef === true) { + echo "\t\t* style definition closed *".PHP_EOL; + } + + if ($asperandStart === true) { + echo "\t\t* at-rule definition closed *".PHP_EOL; + } + } + + $inStyleDef = false; + $asperandStart = false; + break; + case T_MINUS: + // Minus signs are often used instead of spaces inside + // class names, IDs and styles. + if ($finalTokens[($stackPtr + 1)]['code'] === T_STRING) { + if ($finalTokens[($stackPtr - 1)]['code'] === T_STRING) { + $newContent = $finalTokens[($stackPtr - 1)]['content'].'-'.$finalTokens[($stackPtr + 1)]['content']; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is a string joiner; ignoring this and previous token".PHP_EOL; + $old = Util\Common::prepareForOutput($finalTokens[($stackPtr + 1)]['content']); + $new = Util\Common::prepareForOutput($newContent); + echo "\t\t=> token ".($stackPtr + 1)." content changed from \"$old\" to \"$new\"".PHP_EOL; + } + + $finalTokens[($stackPtr + 1)]['content'] = $newContent; + unset($finalTokens[$stackPtr]); + unset($finalTokens[($stackPtr - 1)]); + } else { + $newContent = '-'.$finalTokens[($stackPtr + 1)]['content']; + + $finalTokens[($stackPtr + 1)]['content'] = $newContent; + unset($finalTokens[$stackPtr]); + } + } else if ($finalTokens[($stackPtr + 1)]['code'] === T_LNUMBER) { + // They can also be used to provide negative numbers. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is part of a negative number; adding content to next token and ignoring *".PHP_EOL; + $content = Util\Common::prepareForOutput($finalTokens[($stackPtr + 1)]['content']); + echo "\t\t=> token ".($stackPtr + 1)." content changed from \"$content\" to \"-$content\"".PHP_EOL; + } + + $finalTokens[($stackPtr + 1)]['content'] = '-'.$finalTokens[($stackPtr + 1)]['content']; + unset($finalTokens[$stackPtr]); + }//end if + break; + case T_COLON: + // Only interested in colons that are defining styles. + if ($inStyleDef === false) { + break; + } + + for ($x = ($stackPtr - 1); $x >= 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$finalTokens[$x]['code']]) === false) { + break; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $finalTokens[$x]['type']; + echo "\t\t=> token $x changed from $type to T_STYLE".PHP_EOL; + } + + $finalTokens[$x]['type'] = 'T_STYLE'; + $finalTokens[$x]['code'] = T_STYLE; + break; + case T_STRING: + if (strtolower($token['content']) === 'url') { + // Find the next content. + for ($x = ($stackPtr + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$finalTokens[$x]['code']]) === false) { + break; + } + } + + // Needs to be in the format "url(" for it to be a URL. + if ($finalTokens[$x]['code'] !== T_OPEN_PARENTHESIS) { + continue 2; + } + + // Make sure the content isn't empty. + for ($y = ($x + 1); $y < $numTokens; $y++) { + if (isset(Util\Tokens::$emptyTokens[$finalTokens[$y]['code']]) === false) { + break; + } + } + + if ($finalTokens[$y]['code'] === T_CLOSE_PARENTHESIS) { + continue 2; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + for ($i = ($stackPtr + 1); $i <= $y; $i++) { + $type = $finalTokens[$i]['type']; + $content = Util\Common::prepareForOutput($finalTokens[$i]['content']); + echo "\tProcess token $i: $type => $content".PHP_EOL; + } + + echo "\t\t* token starts a URL *".PHP_EOL; + } + + // Join all the content together inside the url() statement. + $newContent = ''; + for ($i = ($x + 2); $i < $numTokens; $i++) { + if ($finalTokens[$i]['code'] === T_CLOSE_PARENTHESIS) { + break; + } + + $newContent .= $finalTokens[$i]['content']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($finalTokens[$i]['content']); + echo "\t\t=> token $i added to URL string and ignored: $content".PHP_EOL; + } + + unset($finalTokens[$i]); + } + + $stackPtr = $i; + + // If the content inside the "url()" is in double quotes + // there will only be one token and so we don't have to do + // anything except change its type. If it is not empty, + // we need to do some token merging. + $finalTokens[($x + 1)]['type'] = 'T_URL'; + $finalTokens[($x + 1)]['code'] = T_URL; + + if ($newContent !== '') { + $finalTokens[($x + 1)]['content'] .= $newContent; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($finalTokens[($x + 1)]['content']); + echo "\t\t=> token content changed to: $content".PHP_EOL; + } + } + } else if ($finalTokens[$stackPtr]['content'][0] === '-' + && $finalTokens[($stackPtr + 1)]['code'] === T_STRING + ) { + if (isset($finalTokens[($stackPtr - 1)]) === true + && $finalTokens[($stackPtr - 1)]['code'] === T_STRING + ) { + $newContent = $finalTokens[($stackPtr - 1)]['content'].$finalTokens[$stackPtr]['content'].$finalTokens[($stackPtr + 1)]['content']; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is a string joiner; ignoring this and previous token".PHP_EOL; + $old = Util\Common::prepareForOutput($finalTokens[($stackPtr + 1)]['content']); + $new = Util\Common::prepareForOutput($newContent); + echo "\t\t=> token ".($stackPtr + 1)." content changed from \"$old\" to \"$new\"".PHP_EOL; + } + + $finalTokens[($stackPtr + 1)]['content'] = $newContent; + unset($finalTokens[$stackPtr]); + unset($finalTokens[($stackPtr - 1)]); + } else { + $newContent = $finalTokens[$stackPtr]['content'].$finalTokens[($stackPtr + 1)]['content']; + + $finalTokens[($stackPtr + 1)]['content'] = $newContent; + unset($finalTokens[$stackPtr]); + } + }//end if + break; + case T_ASPERAND: + $asperandStart = true; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* at-rule definition opened *".PHP_EOL; + } + break; + default: + // Nothing special to be done with this token. + break; + }//end switch + }//end for + + // Reset the array keys to avoid gaps. + $finalTokens = array_values($finalTokens); + $numTokens = count($finalTokens); + + // Blank out the content of the end tag. + $finalTokens[($numTokens - 1)]['content'] = ''; + + if ($eolAdded === true) { + // Strip off the extra EOL char we added for tokenizing. + $finalTokens[($numTokens - 2)]['content'] = substr( + $finalTokens[($numTokens - 2)]['content'], + 0, + (strlen($this->eolChar) * -1) + ); + + if ($finalTokens[($numTokens - 2)]['content'] === '') { + unset($finalTokens[($numTokens - 2)]); + $finalTokens = array_values($finalTokens); + $numTokens = count($finalTokens); + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END CSS TOKENIZING 2ND PASS ***".PHP_EOL; + } + + return $finalTokens; + + }//end tokenize() + + + /** + * Performs additional processing after main tokenizing. + * + * @return void + */ + public function processAdditional() + { + /* + We override this method because we don't want the PHP version to + run during CSS processing because it is wasted processing time. + */ + + }//end processAdditional() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Tokenizers/Comment.php b/vendor/squizlabs/php_codesniffer/src/Tokenizers/Comment.php new file mode 100644 index 0000000..9ca2ddf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Tokenizers/Comment.php @@ -0,0 +1,277 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tokenizers; + +use PHP_CodeSniffer\Util; + +class Comment +{ + + + /** + * Creates an array of tokens when given some PHP code. + * + * Starts by using token_get_all() but does a lot of extra processing + * to insert information about the context of the token. + * + * @param string $string The string to tokenize. + * @param string $eolChar The EOL character to use for splitting strings. + * @param int $stackPtr The position of the first token in the file. + * + * @return array + */ + public function tokenizeString($string, $eolChar, $stackPtr) + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t*** START COMMENT TOKENIZING ***".PHP_EOL; + } + + $tokens = []; + $numChars = strlen($string); + + /* + Doc block comments start with /*, but typically contain an + extra star when they are used for function and class comments. + */ + + $char = ($numChars - strlen(ltrim($string, '/*'))); + $openTag = substr($string, 0, $char); + $string = ltrim($string, '/*'); + + $tokens[$stackPtr] = [ + 'content' => $openTag, + 'code' => T_DOC_COMMENT_OPEN_TAG, + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'comment_tags' => [], + ]; + + $openPtr = $stackPtr; + $stackPtr++; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($openTag); + echo "\t\tCreate comment token: T_DOC_COMMENT_OPEN_TAG => $content".PHP_EOL; + } + + /* + Strip off the close tag so it doesn't interfere with any + of our comment line processing. The token will be added to the + stack just before we return it. + */ + + $closeTag = [ + 'content' => substr($string, strlen(rtrim($string, '/*'))), + 'code' => T_DOC_COMMENT_CLOSE_TAG, + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'comment_opener' => $openPtr, + ]; + + if ($closeTag['content'] === false) { + $closeTag['content'] = ''; + } + + $string = rtrim($string, '/*'); + + /* + Process each line of the comment. + */ + + $lines = explode($eolChar, $string); + $numLines = count($lines); + foreach ($lines as $lineNum => $string) { + if ($lineNum !== ($numLines - 1)) { + $string .= $eolChar; + } + + $char = 0; + $numChars = strlen($string); + + // We've started a new line, so process the indent. + $space = $this->collectWhitespace($string, $char, $numChars); + if ($space !== null) { + $tokens[$stackPtr] = $space; + $stackPtr++; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($space['content']); + echo "\t\tCreate comment token: T_DOC_COMMENT_WHITESPACE => $content".PHP_EOL; + } + + $char += strlen($space['content']); + if ($char === $numChars) { + break; + } + } + + if ($string === '') { + continue; + } + + if ($lineNum > 0 && $string[$char] === '*') { + // This is a function or class doc block line. + $char++; + $tokens[$stackPtr] = [ + 'content' => '*', + 'code' => T_DOC_COMMENT_STAR, + 'type' => 'T_DOC_COMMENT_STAR', + ]; + + $stackPtr++; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\tCreate comment token: T_DOC_COMMENT_STAR => *".PHP_EOL; + } + } + + // Now we are ready to process the actual content of the line. + $lineTokens = $this->processLine($string, $eolChar, $char, $numChars); + foreach ($lineTokens as $lineToken) { + $tokens[$stackPtr] = $lineToken; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($lineToken['content']); + $type = $lineToken['type']; + echo "\t\tCreate comment token: $type => $content".PHP_EOL; + } + + if ($lineToken['code'] === T_DOC_COMMENT_TAG) { + $tokens[$openPtr]['comment_tags'][] = $stackPtr; + } + + $stackPtr++; + } + }//end foreach + + $tokens[$stackPtr] = $closeTag; + $tokens[$openPtr]['comment_closer'] = $stackPtr; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($closeTag['content']); + echo "\t\tCreate comment token: T_DOC_COMMENT_CLOSE_TAG => $content".PHP_EOL; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t*** END COMMENT TOKENIZING ***".PHP_EOL; + } + + return $tokens; + + }//end tokenizeString() + + + /** + * Process a single line of a comment. + * + * @param string $string The comment string being tokenized. + * @param string $eolChar The EOL character to use for splitting strings. + * @param int $start The position in the string to start processing. + * @param int $end The position in the string to end processing. + * + * @return array + */ + private function processLine($string, $eolChar, $start, $end) + { + $tokens = []; + + // Collect content padding. + $space = $this->collectWhitespace($string, $start, $end); + if ($space !== null) { + $tokens[] = $space; + $start += strlen($space['content']); + } + + if (isset($string[$start]) === false) { + return $tokens; + } + + if ($string[$start] === '@') { + // The content up until the first whitespace is the tag name. + $matches = []; + preg_match('/@[^\s]+/', $string, $matches, 0, $start); + if (isset($matches[0]) === true + && substr(strtolower($matches[0]), 0, 7) !== '@phpcs:' + ) { + $tagName = $matches[0]; + $start += strlen($tagName); + $tokens[] = [ + 'content' => $tagName, + 'code' => T_DOC_COMMENT_TAG, + 'type' => 'T_DOC_COMMENT_TAG', + ]; + + // Then there will be some whitespace. + $space = $this->collectWhitespace($string, $start, $end); + if ($space !== null) { + $tokens[] = $space; + $start += strlen($space['content']); + } + } + }//end if + + // Process the rest of the line. + $eol = strpos($string, $eolChar, $start); + if ($eol === false) { + $eol = $end; + } + + if ($eol > $start) { + $tokens[] = [ + 'content' => substr($string, $start, ($eol - $start)), + 'code' => T_DOC_COMMENT_STRING, + 'type' => 'T_DOC_COMMENT_STRING', + ]; + } + + if ($eol !== $end) { + $tokens[] = [ + 'content' => substr($string, $eol, strlen($eolChar)), + 'code' => T_DOC_COMMENT_WHITESPACE, + 'type' => 'T_DOC_COMMENT_WHITESPACE', + ]; + } + + return $tokens; + + }//end processLine() + + + /** + * Collect consecutive whitespace into a single token. + * + * @param string $string The comment string being tokenized. + * @param int $start The position in the string to start processing. + * @param int $end The position in the string to end processing. + * + * @return array|null + */ + private function collectWhitespace($string, $start, $end) + { + $space = ''; + for ($start; $start < $end; $start++) { + if ($string[$start] !== ' ' && $string[$start] !== "\t") { + break; + } + + $space .= $string[$start]; + } + + if ($space === '') { + return null; + } + + $token = [ + 'content' => $space, + 'code' => T_DOC_COMMENT_WHITESPACE, + 'type' => 'T_DOC_COMMENT_WHITESPACE', + ]; + + return $token; + + }//end collectWhitespace() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Tokenizers/JS.php b/vendor/squizlabs/php_codesniffer/src/Tokenizers/JS.php new file mode 100644 index 0000000..cb7bd3c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Tokenizers/JS.php @@ -0,0 +1,1256 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tokenizers; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\TokenizerException; +use PHP_CodeSniffer\Util; + +class JS extends Tokenizer +{ + + /** + * A list of tokens that are allowed to open a scope. + * + * This array also contains information about what kind of token the scope + * opener uses to open and close the scope, if the token strictly requires + * an opener, if the token can share a scope closer, and who it can be shared + * with. An example of a token that shares a scope closer is a CASE scope. + * + * @var array + */ + public $scopeOpeners = [ + T_IF => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_TRY => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_CATCH => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_ELSE => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_FOR => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_CLASS => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_FUNCTION => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_WHILE => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_DO => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_SWITCH => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_CASE => [ + 'start' => [T_COLON => T_COLON], + 'end' => [ + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + T_CONTINUE => T_CONTINUE, + T_THROW => T_THROW, + ], + 'strict' => true, + 'shared' => true, + 'with' => [ + T_DEFAULT => T_DEFAULT, + T_CASE => T_CASE, + T_SWITCH => T_SWITCH, + ], + ], + T_DEFAULT => [ + 'start' => [T_COLON => T_COLON], + 'end' => [ + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + T_CONTINUE => T_CONTINUE, + T_THROW => T_THROW, + ], + 'strict' => true, + 'shared' => true, + 'with' => [ + T_CASE => T_CASE, + T_SWITCH => T_SWITCH, + ], + ], + ]; + + /** + * A list of tokens that end the scope. + * + * This array is just a unique collection of the end tokens + * from the _scopeOpeners array. The data is duplicated here to + * save time during parsing of the file. + * + * @var array + */ + public $endScopeTokens = [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_BREAK => T_BREAK, + ]; + + /** + * A list of special JS tokens and their types. + * + * @var array + */ + protected $tokenValues = [ + 'class' => 'T_CLASS', + 'function' => 'T_FUNCTION', + 'prototype' => 'T_PROTOTYPE', + 'try' => 'T_TRY', + 'catch' => 'T_CATCH', + 'return' => 'T_RETURN', + 'throw' => 'T_THROW', + 'break' => 'T_BREAK', + 'switch' => 'T_SWITCH', + 'continue' => 'T_CONTINUE', + 'if' => 'T_IF', + 'else' => 'T_ELSE', + 'do' => 'T_DO', + 'while' => 'T_WHILE', + 'for' => 'T_FOR', + 'var' => 'T_VAR', + 'case' => 'T_CASE', + 'default' => 'T_DEFAULT', + 'true' => 'T_TRUE', + 'false' => 'T_FALSE', + 'null' => 'T_NULL', + 'this' => 'T_THIS', + 'typeof' => 'T_TYPEOF', + '(' => 'T_OPEN_PARENTHESIS', + ')' => 'T_CLOSE_PARENTHESIS', + '{' => 'T_OPEN_CURLY_BRACKET', + '}' => 'T_CLOSE_CURLY_BRACKET', + '[' => 'T_OPEN_SQUARE_BRACKET', + ']' => 'T_CLOSE_SQUARE_BRACKET', + '?' => 'T_INLINE_THEN', + '.' => 'T_OBJECT_OPERATOR', + '+' => 'T_PLUS', + '-' => 'T_MINUS', + '*' => 'T_MULTIPLY', + '%' => 'T_MODULUS', + '/' => 'T_DIVIDE', + '^' => 'T_LOGICAL_XOR', + ',' => 'T_COMMA', + ';' => 'T_SEMICOLON', + ':' => 'T_COLON', + '<' => 'T_LESS_THAN', + '>' => 'T_GREATER_THAN', + '<<' => 'T_SL', + '>>' => 'T_SR', + '>>>' => 'T_ZSR', + '<<=' => 'T_SL_EQUAL', + '>>=' => 'T_SR_EQUAL', + '>>>=' => 'T_ZSR_EQUAL', + '<=' => 'T_IS_SMALLER_OR_EQUAL', + '>=' => 'T_IS_GREATER_OR_EQUAL', + '=>' => 'T_DOUBLE_ARROW', + '!' => 'T_BOOLEAN_NOT', + '||' => 'T_BOOLEAN_OR', + '&&' => 'T_BOOLEAN_AND', + '|' => 'T_BITWISE_OR', + '&' => 'T_BITWISE_AND', + '!=' => 'T_IS_NOT_EQUAL', + '!==' => 'T_IS_NOT_IDENTICAL', + '=' => 'T_EQUAL', + '==' => 'T_IS_EQUAL', + '===' => 'T_IS_IDENTICAL', + '-=' => 'T_MINUS_EQUAL', + '+=' => 'T_PLUS_EQUAL', + '*=' => 'T_MUL_EQUAL', + '/=' => 'T_DIV_EQUAL', + '%=' => 'T_MOD_EQUAL', + '++' => 'T_INC', + '--' => 'T_DEC', + '//' => 'T_COMMENT', + '/*' => 'T_COMMENT', + '/**' => 'T_DOC_COMMENT', + '*/' => 'T_COMMENT', + ]; + + /** + * A list string delimiters. + * + * @var array + */ + protected $stringTokens = [ + '\'' => '\'', + '"' => '"', + ]; + + /** + * A list tokens that start and end comments. + * + * @var array + */ + protected $commentTokens = [ + '//' => null, + '/*' => '*/', + '/**' => '*/', + ]; + + + /** + * Initialise the tokenizer. + * + * Pre-checks the content to see if it looks minified. + * + * @param string $content The content to tokenize, + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param string $eolChar The EOL char used in the content. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\TokenizerException If the file appears to be minified. + */ + public function __construct($content, Config $config, $eolChar='\n') + { + if ($this->isMinifiedContent($content, $eolChar) === true) { + throw new TokenizerException('File appears to be minified and cannot be processed'); + } + + parent::__construct($content, $config, $eolChar); + + }//end __construct() + + + /** + * Creates an array of tokens when given some JS code. + * + * @param string $string The string to tokenize. + * + * @return array + */ + public function tokenize($string) + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START JS TOKENIZING ***".PHP_EOL; + } + + $maxTokenLength = 0; + foreach ($this->tokenValues as $token => $values) { + if (strlen($token) > $maxTokenLength) { + $maxTokenLength = strlen($token); + } + } + + $tokens = []; + $inString = ''; + $stringChar = null; + $inComment = ''; + $buffer = ''; + $preStringBuffer = ''; + $cleanBuffer = false; + + $commentTokenizer = new Comment(); + + $tokens[] = [ + 'code' => T_OPEN_TAG, + 'type' => 'T_OPEN_TAG', + 'content' => '', + ]; + + // Convert newlines to single characters for ease of + // processing. We will change them back later. + $string = str_replace($this->eolChar, "\n", $string); + + $chars = str_split($string); + $numChars = count($chars); + for ($i = 0; $i < $numChars; $i++) { + $char = $chars[$i]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($char); + $bufferContent = Util\Common::prepareForOutput($buffer); + + if ($inString !== '') { + echo "\t"; + } + + if ($inComment !== '') { + echo "\t"; + } + + echo "\tProcess char $i => $content (buffer: $bufferContent)".PHP_EOL; + }//end if + + if ($inString === '' && $inComment === '' && $buffer !== '') { + // If the buffer only has whitespace and we are about to + // add a character, store the whitespace first. + if (trim($char) !== '' && trim($buffer) === '') { + $tokens[] = [ + 'code' => T_WHITESPACE, + 'type' => 'T_WHITESPACE', + 'content' => str_replace("\n", $this->eolChar, $buffer), + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token T_WHITESPACE ($content)".PHP_EOL; + } + + $buffer = ''; + } + + // If the buffer is not whitespace and we are about to + // add a whitespace character, store the content first. + if ($inString === '' + && $inComment === '' + && trim($char) === '' + && trim($buffer) !== '' + ) { + $tokens[] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => str_replace("\n", $this->eolChar, $buffer), + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token T_STRING ($content)".PHP_EOL; + } + + $buffer = ''; + } + }//end if + + // Process strings. + if ($inComment === '' && isset($this->stringTokens[$char]) === true) { + if ($inString === $char) { + // This could be the end of the string, but make sure it + // is not escaped first. + $escapes = 0; + for ($x = ($i - 1); $x >= 0; $x--) { + if ($chars[$x] !== '\\') { + break; + } + + $escapes++; + } + + if ($escapes === 0 || ($escapes % 2) === 0) { + // There is an even number escape chars, + // so this is not escaped, it is the end of the string. + $tokens[] = [ + 'code' => T_CONSTANT_ENCAPSED_STRING, + 'type' => 'T_CONSTANT_ENCAPSED_STRING', + 'content' => str_replace("\n", $this->eolChar, $buffer).$char, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* found end of string *".PHP_EOL; + $content = Util\Common::prepareForOutput($buffer.$char); + echo "\t=> Added token T_CONSTANT_ENCAPSED_STRING ($content)".PHP_EOL; + } + + $buffer = ''; + $preStringBuffer = ''; + $inString = ''; + $stringChar = null; + continue; + }//end if + } else if ($inString === '') { + $inString = $char; + $stringChar = $i; + $preStringBuffer = $buffer; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* looking for string closer *".PHP_EOL; + } + }//end if + }//end if + + if ($inString !== '' && $char === "\n") { + // Unless this newline character is escaped, the string did not + // end before the end of the line, which means it probably + // wasn't a string at all (maybe a regex). + if ($chars[($i - 1)] !== '\\') { + $i = $stringChar; + $buffer = $preStringBuffer; + $preStringBuffer = ''; + $inString = ''; + $stringChar = null; + $char = $chars[$i]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* found newline before end of string, bailing *".PHP_EOL; + } + } + } + + $buffer .= $char; + + // We don't look for special tokens inside strings, + // so if we are in a string, we can continue here now + // that the current char is in the buffer. + if ($inString !== '') { + continue; + } + + // Special case for T_DIVIDE which can actually be + // the start of a regular expression. + if ($buffer === $char && $char === '/' && $chars[($i + 1)] !== '*') { + $regex = $this->getRegexToken($i, $string, $chars, $tokens); + if ($regex !== null) { + $tokens[] = [ + 'code' => T_REGULAR_EXPRESSION, + 'type' => 'T_REGULAR_EXPRESSION', + 'content' => $regex['content'], + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($regex['content']); + echo "\t=> Added token T_REGULAR_EXPRESSION ($content)".PHP_EOL; + } + + $i = $regex['end']; + $buffer = ''; + $cleanBuffer = false; + continue; + }//end if + }//end if + + // Check for known tokens, but ignore tokens found that are not at + // the end of a string, like FOR and this.FORmat. + if (isset($this->tokenValues[strtolower($buffer)]) === true + && (preg_match('|[a-zA-z0-9_]|', $char) === 0 + || isset($chars[($i + 1)]) === false + || preg_match('|[a-zA-z0-9_]|', $chars[($i + 1)]) === 0) + ) { + $matchedToken = false; + $lookAheadLength = ($maxTokenLength - strlen($buffer)); + + if ($lookAheadLength > 0) { + // The buffer contains a token type, but we need + // to look ahead at the next chars to see if this is + // actually part of a larger token. For example, + // FOR and FOREACH. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* buffer possibly contains token, looking ahead $lookAheadLength chars *".PHP_EOL; + } + + $charBuffer = $buffer; + for ($x = 1; $x <= $lookAheadLength; $x++) { + if (isset($chars[($i + $x)]) === false) { + break; + } + + $charBuffer .= $chars[($i + $x)]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($charBuffer); + echo "\t\t=> Looking ahead $x chars => $content".PHP_EOL; + } + + if (isset($this->tokenValues[strtolower($charBuffer)]) === true) { + // We've found something larger that matches + // so we can ignore this char. Except for 1 very specific + // case where a comment like /**/ needs to tokenize as + // T_COMMENT and not T_DOC_COMMENT. + $oldType = $this->tokenValues[strtolower($buffer)]; + $newType = $this->tokenValues[strtolower($charBuffer)]; + if ($oldType === 'T_COMMENT' + && $newType === 'T_DOC_COMMENT' + && $chars[($i + $x + 1)] === '/' + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* look ahead ignored T_DOC_COMMENT, continuing *".PHP_EOL; + } + } else { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* look ahead found more specific token ($newType), ignoring $i *".PHP_EOL; + } + + $matchedToken = true; + break; + } + }//end if + }//end for + }//end if + + if ($matchedToken === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1 && $lookAheadLength > 0) { + echo "\t\t* look ahead found nothing *".PHP_EOL; + } + + $value = $this->tokenValues[strtolower($buffer)]; + + if ($value === 'T_FUNCTION' && $buffer !== 'function') { + // The function keyword needs to be all lowercase or else + // it is just a function called "Function". + $value = 'T_STRING'; + } + + $tokens[] = [ + 'code' => constant($value), + 'type' => $value, + 'content' => $buffer, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token $value ($content)".PHP_EOL; + } + + $cleanBuffer = true; + }//end if + } else if (isset($this->tokenValues[strtolower($char)]) === true) { + // No matter what token we end up using, we don't + // need the content in the buffer any more because we have + // found a valid token. + $newContent = substr(str_replace("\n", $this->eolChar, $buffer), 0, -1); + if ($newContent !== '') { + $tokens[] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => $newContent, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput(substr($buffer, 0, -1)); + echo "\t=> Added token T_STRING ($content)".PHP_EOL; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* char is token, looking ahead ".($maxTokenLength - 1).' chars *'.PHP_EOL; + } + + // The char is a token type, but we need to look ahead at the + // next chars to see if this is actually part of a larger token. + // For example, = and ===. + $charBuffer = $char; + $matchedToken = false; + for ($x = 1; $x <= $maxTokenLength; $x++) { + if (isset($chars[($i + $x)]) === false) { + break; + } + + $charBuffer .= $chars[($i + $x)]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($charBuffer); + echo "\t\t=> Looking ahead $x chars => $content".PHP_EOL; + } + + if (isset($this->tokenValues[strtolower($charBuffer)]) === true) { + // We've found something larger that matches + // so we can ignore this char. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokenValues[strtolower($charBuffer)]; + echo "\t\t* look ahead found more specific token ($type), ignoring $i *".PHP_EOL; + } + + $matchedToken = true; + break; + } + }//end for + + if ($matchedToken === false) { + $value = $this->tokenValues[strtolower($char)]; + $tokens[] = [ + 'code' => constant($value), + 'type' => $value, + 'content' => $char, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* look ahead found nothing *".PHP_EOL; + $content = Util\Common::prepareForOutput($char); + echo "\t=> Added token $value ($content)".PHP_EOL; + } + + $cleanBuffer = true; + } else { + $buffer = $char; + }//end if + }//end if + + // Keep track of content inside comments. + if ($inComment === '' + && array_key_exists($buffer, $this->commentTokens) === true + ) { + // This is not really a comment if the content + // looks like \// (i.e., it is escaped). + if (isset($chars[($i - 2)]) === true && $chars[($i - 2)] === '\\') { + $lastToken = array_pop($tokens); + $lastContent = $lastToken['content']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $value = $this->tokenValues[strtolower($lastContent)]; + $content = Util\Common::prepareForOutput($lastContent); + echo "\t=> Removed token $value ($content)".PHP_EOL; + } + + $lastChars = str_split($lastContent); + $lastNumChars = count($lastChars); + for ($x = 0; $x < $lastNumChars; $x++) { + $lastChar = $lastChars[$x]; + $value = $this->tokenValues[strtolower($lastChar)]; + $tokens[] = [ + 'code' => constant($value), + 'type' => $value, + 'content' => $lastChar, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($lastChar); + echo "\t=> Added token $value ($content)".PHP_EOL; + } + } + } else { + // We have started a comment. + $inComment = $buffer; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* looking for end of comment *".PHP_EOL; + } + }//end if + } else if ($inComment !== '') { + if ($this->commentTokens[$inComment] === null) { + // Comment ends at the next newline. + if (strpos($buffer, "\n") !== false) { + $inComment = ''; + } + } else { + if ($this->commentTokens[$inComment] === $buffer) { + $inComment = ''; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if ($inComment === '') { + echo "\t\t* found end of comment *".PHP_EOL; + } + } + + if ($inComment === '' && $cleanBuffer === false) { + $tokens[] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => str_replace("\n", $this->eolChar, $buffer), + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token T_STRING ($content)".PHP_EOL; + } + + $buffer = ''; + } + }//end if + + if ($cleanBuffer === true) { + $buffer = ''; + $cleanBuffer = false; + } + }//end for + + if (empty($buffer) === false) { + if ($inString !== '') { + // The string did not end before the end of the file, + // which means there was probably a syntax error somewhere. + $tokens[] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => str_replace("\n", $this->eolChar, $buffer), + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token T_STRING ($content)".PHP_EOL; + } + } else { + // Buffer contains whitespace from the end of the file. + $tokens[] = [ + 'code' => T_WHITESPACE, + 'type' => 'T_WHITESPACE', + 'content' => str_replace("\n", $this->eolChar, $buffer), + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $content = Util\Common::prepareForOutput($buffer); + echo "\t=> Added token T_WHITESPACE ($content)".PHP_EOL; + } + }//end if + }//end if + + $tokens[] = [ + 'code' => T_CLOSE_TAG, + 'type' => 'T_CLOSE_TAG', + 'content' => '', + ]; + + /* + Now that we have done some basic tokenizing, we need to + modify the tokens to join some together and split some apart + so they match what the PHP tokenizer does. + */ + + $finalTokens = []; + $newStackPtr = 0; + $numTokens = count($tokens); + for ($stackPtr = 0; $stackPtr < $numTokens; $stackPtr++) { + $token = $tokens[$stackPtr]; + + /* + Look for comments and join the tokens together. + */ + + if ($token['code'] === T_COMMENT || $token['code'] === T_DOC_COMMENT) { + $newContent = ''; + $tokenContent = $token['content']; + + $endContent = null; + if (isset($this->commentTokens[$tokenContent]) === true) { + $endContent = $this->commentTokens[$tokenContent]; + } + + while ($tokenContent !== $endContent) { + if ($endContent === null + && strpos($tokenContent, $this->eolChar) !== false + ) { + // A null end token means the comment ends at the end of + // the line so we look for newlines and split the token. + $tokens[$stackPtr]['content'] = substr( + $tokenContent, + (strpos($tokenContent, $this->eolChar) + strlen($this->eolChar)) + ); + + $tokenContent = substr( + $tokenContent, + 0, + (strpos($tokenContent, $this->eolChar) + strlen($this->eolChar)) + ); + + // If the substr failed, skip the token as the content + // will now be blank. + if ($tokens[$stackPtr]['content'] !== false + && $tokens[$stackPtr]['content'] !== '' + ) { + $stackPtr--; + } + + break; + }//end if + + $stackPtr++; + $newContent .= $tokenContent; + if (isset($tokens[$stackPtr]) === false) { + break; + } + + $tokenContent = $tokens[$stackPtr]['content']; + }//end while + + if ($token['code'] === T_DOC_COMMENT) { + $commentTokens = $commentTokenizer->tokenizeString($newContent.$tokenContent, $this->eolChar, $newStackPtr); + foreach ($commentTokens as $commentToken) { + $finalTokens[$newStackPtr] = $commentToken; + $newStackPtr++; + } + + continue; + } else { + // Save the new content in the current token so + // the code below can chop it up on newlines. + $token['content'] = $newContent.$tokenContent; + } + }//end if + + /* + If this token has newlines in its content, split each line up + and create a new token for each line. We do this so it's easier + to ascertain where errors occur on a line. + Note that $token[1] is the token's content. + */ + + if (strpos($token['content'], $this->eolChar) !== false) { + $tokenLines = explode($this->eolChar, $token['content']); + $numLines = count($tokenLines); + + for ($i = 0; $i < $numLines; $i++) { + $newToken = ['content' => $tokenLines[$i]]; + if ($i === ($numLines - 1)) { + if ($tokenLines[$i] === '') { + break; + } + } else { + $newToken['content'] .= $this->eolChar; + } + + $newToken['type'] = $token['type']; + $newToken['code'] = $token['code']; + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + } + } else { + $finalTokens[$newStackPtr] = $token; + $newStackPtr++; + }//end if + + // Convert numbers, including decimals. + if ($token['code'] === T_STRING + || $token['code'] === T_OBJECT_OPERATOR + ) { + $newContent = ''; + $oldStackPtr = $stackPtr; + while (preg_match('|^[0-9\.]+$|', $tokens[$stackPtr]['content']) !== 0) { + $newContent .= $tokens[$stackPtr]['content']; + $stackPtr++; + } + + if ($newContent !== '' && $newContent !== '.') { + $finalTokens[($newStackPtr - 1)]['content'] = $newContent; + if (ctype_digit($newContent) === true) { + $finalTokens[($newStackPtr - 1)]['code'] = constant('T_LNUMBER'); + $finalTokens[($newStackPtr - 1)]['type'] = 'T_LNUMBER'; + } else { + $finalTokens[($newStackPtr - 1)]['code'] = constant('T_DNUMBER'); + $finalTokens[($newStackPtr - 1)]['type'] = 'T_DNUMBER'; + } + + $stackPtr--; + continue; + } else { + $stackPtr = $oldStackPtr; + } + }//end if + + // Convert the token after an object operator into a string, in most cases. + if ($token['code'] === T_OBJECT_OPERATOR) { + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (isset(Util\Tokens::$emptyTokens[$tokens[$i]['code']]) === true) { + continue; + } + + if ($tokens[$i]['code'] !== T_PROTOTYPE + && $tokens[$i]['code'] !== T_LNUMBER + && $tokens[$i]['code'] !== T_DNUMBER + ) { + $tokens[$i]['code'] = T_STRING; + $tokens[$i]['type'] = 'T_STRING'; + } + + break; + } + } + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END TOKENIZING ***".PHP_EOL; + } + + return $finalTokens; + + }//end tokenize() + + + /** + * Tokenizes a regular expression if one is found. + * + * If a regular expression is not found, NULL is returned. + * + * @param int $char The index of the possible regex start character. + * @param string $string The complete content of the string being tokenized. + * @param array $chars An array of characters being tokenized. + * @param array $tokens The current array of tokens found in the string. + * + * @return array|null + */ + public function getRegexToken($char, $string, $chars, $tokens) + { + $beforeTokens = [ + T_EQUAL => true, + T_IS_NOT_EQUAL => true, + T_IS_IDENTICAL => true, + T_IS_NOT_IDENTICAL => true, + T_OPEN_PARENTHESIS => true, + T_OPEN_SQUARE_BRACKET => true, + T_RETURN => true, + T_BOOLEAN_OR => true, + T_BOOLEAN_AND => true, + T_BOOLEAN_NOT => true, + T_BITWISE_OR => true, + T_BITWISE_AND => true, + T_COMMA => true, + T_COLON => true, + T_TYPEOF => true, + T_INLINE_THEN => true, + T_INLINE_ELSE => true, + ]; + + $afterTokens = [ + ',' => true, + ')' => true, + ']' => true, + ';' => true, + ' ' => true, + '.' => true, + ':' => true, + $this->eolChar => true, + ]; + + // Find the last non-whitespace token that was added + // to the tokens array. + $numTokens = count($tokens); + for ($prev = ($numTokens - 1); $prev >= 0; $prev--) { + if (isset(Util\Tokens::$emptyTokens[$tokens[$prev]['code']]) === false) { + break; + } + } + + if (isset($beforeTokens[$tokens[$prev]['code']]) === false) { + return null; + } + + // This is probably a regular expression, so look for the end of it. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* token possibly starts a regular expression *".PHP_EOL; + } + + $numChars = count($chars); + for ($next = ($char + 1); $next < $numChars; $next++) { + if ($chars[$next] === '/') { + // Just make sure this is not escaped first. + if ($chars[($next - 1)] !== '\\') { + // In the simple form: /.../ so we found the end. + break; + } else if ($chars[($next - 2)] === '\\') { + // In the form: /...\\/ so we found the end. + break; + } + } else { + $possibleEolChar = substr($string, $next, strlen($this->eolChar)); + if ($possibleEolChar === $this->eolChar) { + // This is the last token on the line and regular + // expressions need to be defined on a single line, + // so this is not a regular expression. + break; + } + } + } + + if ($chars[$next] !== '/') { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* could not find end of regular expression *".PHP_EOL; + } + + return null; + } + + while (preg_match('|[a-zA-Z]|', $chars[($next + 1)]) !== 0) { + // The token directly after the end of the regex can + // be modifiers like global and case insensitive + // (.e.g, /pattern/gi). + $next++; + } + + $regexEnd = $next; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* found end of regular expression at token $regexEnd *".PHP_EOL; + } + + for ($next += 1; $next < $numChars; $next++) { + if ($chars[$next] !== ' ') { + break; + } else { + $possibleEolChar = substr($string, $next, strlen($this->eolChar)); + if ($possibleEolChar === $this->eolChar) { + // This is the last token on the line. + break; + } + } + } + + if (isset($afterTokens[$chars[$next]]) === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* tokens after regular expression do not look correct *".PHP_EOL; + } + + return null; + } + + // This is a regular expression, so join all the tokens together. + $content = ''; + for ($x = $char; $x <= $regexEnd; $x++) { + $content .= $chars[$x]; + } + + $token = [ + 'start' => $char, + 'end' => $regexEnd, + 'content' => $content, + ]; + + return $token; + + }//end getRegexToken() + + + /** + * Performs additional processing after main tokenizing. + * + * This additional processing looks for properties, closures, labels and objects. + * + * @return void + */ + public function processAdditional() + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START ADDITIONAL JS PROCESSING ***".PHP_EOL; + } + + $numTokens = count($this->tokens); + $classStack = []; + + for ($i = 0; $i < $numTokens; $i++) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$i]['type']; + $content = Util\Common::prepareForOutput($this->tokens[$i]['content']); + + echo str_repeat("\t", count($classStack)); + echo "\tProcess token $i: $type => $content".PHP_EOL; + } + + // Looking for functions that are actually closures. + if ($this->tokens[$i]['code'] === T_FUNCTION && isset($this->tokens[$i]['scope_opener']) === true) { + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + break; + } + } + + if ($this->tokens[$x]['code'] === T_OPEN_PARENTHESIS) { + $this->tokens[$i]['code'] = T_CLOSURE; + $this->tokens[$i]['type'] = 'T_CLOSURE'; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo str_repeat("\t", count($classStack)); + echo "\t* token $i on line $line changed from T_FUNCTION to T_CLOSURE *".PHP_EOL; + } + + for ($x = ($this->tokens[$i]['scope_opener'] + 1); $x < $this->tokens[$i]['scope_closer']; $x++) { + if (isset($this->tokens[$x]['conditions'][$i]) === false) { + continue; + } + + $this->tokens[$x]['conditions'][$i] = T_CLOSURE; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + echo str_repeat("\t", count($classStack)); + echo "\t\t* cleaned $x ($type) *".PHP_EOL; + } + } + }//end if + + continue; + } else if ($this->tokens[$i]['code'] === T_OPEN_CURLY_BRACKET + && isset($this->tokens[$i]['scope_condition']) === false + && isset($this->tokens[$i]['bracket_closer']) === true + ) { + $condition = $this->tokens[$i]['conditions']; + $condition = end($condition); + if ($condition === T_CLASS) { + // Possibly an ES6 method. To be classified as one, the previous + // non-empty tokens need to be a set of parenthesis, and then a string + // (the method name). + for ($parenCloser = ($i - 1); $parenCloser > 0; $parenCloser--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$parenCloser]['code']]) === false) { + break; + } + } + + if ($this->tokens[$parenCloser]['code'] === T_CLOSE_PARENTHESIS) { + $parenOpener = $this->tokens[$parenCloser]['parenthesis_opener']; + for ($name = ($parenOpener - 1); $name > 0; $name--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$name]['code']]) === false) { + break; + } + } + + if ($this->tokens[$name]['code'] === T_STRING) { + // We found a method name. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$name]['line']; + echo str_repeat("\t", count($classStack)); + echo "\t* token $name on line $line changed from T_STRING to T_FUNCTION *".PHP_EOL; + } + + $closer = $this->tokens[$i]['bracket_closer']; + + $this->tokens[$name]['code'] = T_FUNCTION; + $this->tokens[$name]['type'] = 'T_FUNCTION'; + + foreach ([$name, $i, $closer] as $token) { + $this->tokens[$token]['scope_condition'] = $name; + $this->tokens[$token]['scope_opener'] = $i; + $this->tokens[$token]['scope_closer'] = $closer; + $this->tokens[$token]['parenthesis_opener'] = $parenOpener; + $this->tokens[$token]['parenthesis_closer'] = $parenCloser; + $this->tokens[$token]['parenthesis_owner'] = $name; + } + + $this->tokens[$parenOpener]['parenthesis_owner'] = $name; + $this->tokens[$parenCloser]['parenthesis_owner'] = $name; + + for ($x = ($i + 1); $x < $closer; $x++) { + $this->tokens[$x]['conditions'][$name] = T_FUNCTION; + ksort($this->tokens[$x]['conditions'], SORT_NUMERIC); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + echo str_repeat("\t", count($classStack)); + echo "\t\t* added T_FUNCTION condition to $x ($type) *".PHP_EOL; + } + } + + continue; + }//end if + }//end if + }//end if + + $classStack[] = $i; + + $closer = $this->tokens[$i]['bracket_closer']; + $this->tokens[$i]['code'] = T_OBJECT; + $this->tokens[$i]['type'] = 'T_OBJECT'; + $this->tokens[$closer]['code'] = T_CLOSE_OBJECT; + $this->tokens[$closer]['type'] = 'T_CLOSE_OBJECT'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($classStack)); + echo "\t* token $i converted from T_OPEN_CURLY_BRACKET to T_OBJECT *".PHP_EOL; + echo str_repeat("\t", count($classStack)); + echo "\t* token $closer converted from T_CLOSE_CURLY_BRACKET to T_CLOSE_OBJECT *".PHP_EOL; + } + + for ($x = ($i + 1); $x < $closer; $x++) { + $this->tokens[$x]['conditions'][$i] = T_OBJECT; + ksort($this->tokens[$x]['conditions'], SORT_NUMERIC); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + echo str_repeat("\t", count($classStack)); + echo "\t\t* added T_OBJECT condition to $x ($type) *".PHP_EOL; + } + } + } else if ($this->tokens[$i]['code'] === T_CLOSE_OBJECT) { + $opener = array_pop($classStack); + } else if ($this->tokens[$i]['code'] === T_COLON) { + // If it is a scope opener, it belongs to a + // DEFAULT or CASE statement. + if (isset($this->tokens[$i]['scope_condition']) === true) { + continue; + } + + // Make sure this is not part of an inline IF statement. + for ($x = ($i - 1); $x >= 0; $x--) { + if ($this->tokens[$x]['code'] === T_INLINE_THEN) { + $this->tokens[$i]['code'] = T_INLINE_ELSE; + $this->tokens[$i]['type'] = 'T_INLINE_ELSE'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($classStack)); + echo "\t* token $i converted from T_COLON to T_INLINE_THEN *".PHP_EOL; + } + + continue(2); + } else if ($this->tokens[$x]['line'] < $this->tokens[$i]['line']) { + break; + } + } + + // The string to the left of the colon is either a property or label. + for ($label = ($i - 1); $label >= 0; $label--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$label]['code']]) === false) { + break; + } + } + + if ($this->tokens[$label]['code'] !== T_STRING + && $this->tokens[$label]['code'] !== T_CONSTANT_ENCAPSED_STRING + ) { + continue; + } + + if (empty($classStack) === false) { + $this->tokens[$label]['code'] = T_PROPERTY; + $this->tokens[$label]['type'] = 'T_PROPERTY'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($classStack)); + echo "\t* token $label converted from T_STRING to T_PROPERTY *".PHP_EOL; + } + } else { + $this->tokens[$label]['code'] = T_LABEL; + $this->tokens[$label]['type'] = 'T_LABEL'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($classStack)); + echo "\t* token $label converted from T_STRING to T_LABEL *".PHP_EOL; + } + }//end if + }//end if + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END ADDITIONAL JS PROCESSING ***".PHP_EOL; + } + + }//end processAdditional() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Tokenizers/PHP.php b/vendor/squizlabs/php_codesniffer/src/Tokenizers/PHP.php new file mode 100644 index 0000000..e8ad0db --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Tokenizers/PHP.php @@ -0,0 +1,3632 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tokenizers; + +use PHP_CodeSniffer\Util; + +class PHP extends Tokenizer +{ + + /** + * A list of tokens that are allowed to open a scope. + * + * This array also contains information about what kind of token the scope + * opener uses to open and close the scope, if the token strictly requires + * an opener, if the token can share a scope closer, and who it can be shared + * with. An example of a token that shares a scope closer is a CASE scope. + * + * @var array + */ + public $scopeOpeners = [ + T_IF => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDIF => T_ENDIF, + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + ], + 'strict' => false, + 'shared' => false, + 'with' => [ + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + ], + ], + T_TRY => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_CATCH => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_FINALLY => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_ELSE => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDIF => T_ENDIF, + ], + 'strict' => false, + 'shared' => false, + 'with' => [ + T_IF => T_IF, + T_ELSEIF => T_ELSEIF, + ], + ], + T_ELSEIF => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDIF => T_ENDIF, + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + ], + 'strict' => false, + 'shared' => false, + 'with' => [ + T_IF => T_IF, + T_ELSE => T_ELSE, + ], + ], + T_FOR => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDFOR => T_ENDFOR, + ], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_FOREACH => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDFOREACH => T_ENDFOREACH, + ], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_INTERFACE => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_FUNCTION => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_CLASS => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_TRAIT => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_ENUM => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_USE => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_DECLARE => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDDECLARE => T_ENDDECLARE, + ], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_NAMESPACE => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_WHILE => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDWHILE => T_ENDWHILE, + ], + 'strict' => false, + 'shared' => false, + 'with' => [], + ], + T_DO => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_SWITCH => [ + 'start' => [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_COLON => T_COLON, + ], + 'end' => [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDSWITCH => T_ENDSWITCH, + ], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_CASE => [ + 'start' => [ + T_COLON => T_COLON, + T_SEMICOLON => T_SEMICOLON, + ], + 'end' => [ + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + T_CONTINUE => T_CONTINUE, + T_THROW => T_THROW, + T_EXIT => T_EXIT, + ], + 'strict' => true, + 'shared' => true, + 'with' => [ + T_DEFAULT => T_DEFAULT, + T_CASE => T_CASE, + T_SWITCH => T_SWITCH, + ], + ], + T_DEFAULT => [ + 'start' => [ + T_COLON => T_COLON, + T_SEMICOLON => T_SEMICOLON, + ], + 'end' => [ + T_BREAK => T_BREAK, + T_RETURN => T_RETURN, + T_CONTINUE => T_CONTINUE, + T_THROW => T_THROW, + T_EXIT => T_EXIT, + ], + 'strict' => true, + 'shared' => true, + 'with' => [ + T_CASE => T_CASE, + T_SWITCH => T_SWITCH, + ], + ], + T_MATCH => [ + 'start' => [T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET], + 'end' => [T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_START_HEREDOC => [ + 'start' => [T_START_HEREDOC => T_START_HEREDOC], + 'end' => [T_END_HEREDOC => T_END_HEREDOC], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + T_START_NOWDOC => [ + 'start' => [T_START_NOWDOC => T_START_NOWDOC], + 'end' => [T_END_NOWDOC => T_END_NOWDOC], + 'strict' => true, + 'shared' => false, + 'with' => [], + ], + ]; + + /** + * A list of tokens that end the scope. + * + * This array is just a unique collection of the end tokens + * from the scopeOpeners array. The data is duplicated here to + * save time during parsing of the file. + * + * @var array + */ + public $endScopeTokens = [ + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_ENDIF => T_ENDIF, + T_ENDFOR => T_ENDFOR, + T_ENDFOREACH => T_ENDFOREACH, + T_ENDWHILE => T_ENDWHILE, + T_ENDSWITCH => T_ENDSWITCH, + T_ENDDECLARE => T_ENDDECLARE, + T_BREAK => T_BREAK, + T_END_HEREDOC => T_END_HEREDOC, + T_END_NOWDOC => T_END_NOWDOC, + ]; + + /** + * Known lengths of tokens. + * + * @var array + */ + public $knownLengths = [ + T_ABSTRACT => 8, + T_AND_EQUAL => 2, + T_ARRAY => 5, + T_AS => 2, + T_BOOLEAN_AND => 2, + T_BOOLEAN_OR => 2, + T_BREAK => 5, + T_CALLABLE => 8, + T_CASE => 4, + T_CATCH => 5, + T_CLASS => 5, + T_CLASS_C => 9, + T_CLONE => 5, + T_CONCAT_EQUAL => 2, + T_CONST => 5, + T_CONTINUE => 8, + T_CURLY_OPEN => 2, + T_DEC => 2, + T_DECLARE => 7, + T_DEFAULT => 7, + T_DIR => 7, + T_DIV_EQUAL => 2, + T_DO => 2, + T_DOLLAR_OPEN_CURLY_BRACES => 2, + T_DOUBLE_ARROW => 2, + T_DOUBLE_COLON => 2, + T_ECHO => 4, + T_ELLIPSIS => 3, + T_ELSE => 4, + T_ELSEIF => 6, + T_EMPTY => 5, + T_ENDDECLARE => 10, + T_ENDFOR => 6, + T_ENDFOREACH => 10, + T_ENDIF => 5, + T_ENDSWITCH => 9, + T_ENDWHILE => 8, + T_ENUM => 4, + T_ENUM_CASE => 4, + T_EVAL => 4, + T_EXTENDS => 7, + T_FILE => 8, + T_FINAL => 5, + T_FINALLY => 7, + T_FN => 2, + T_FOR => 3, + T_FOREACH => 7, + T_FUNCTION => 8, + T_FUNC_C => 12, + T_GLOBAL => 6, + T_GOTO => 4, + T_HALT_COMPILER => 15, + T_IF => 2, + T_IMPLEMENTS => 10, + T_INC => 2, + T_INCLUDE => 7, + T_INCLUDE_ONCE => 12, + T_INSTANCEOF => 10, + T_INSTEADOF => 9, + T_INTERFACE => 9, + T_ISSET => 5, + T_IS_EQUAL => 2, + T_IS_GREATER_OR_EQUAL => 2, + T_IS_IDENTICAL => 3, + T_IS_NOT_EQUAL => 2, + T_IS_NOT_IDENTICAL => 3, + T_IS_SMALLER_OR_EQUAL => 2, + T_LINE => 8, + T_LIST => 4, + T_LOGICAL_AND => 3, + T_LOGICAL_OR => 2, + T_LOGICAL_XOR => 3, + T_MATCH => 5, + T_MATCH_ARROW => 2, + T_MATCH_DEFAULT => 7, + T_METHOD_C => 10, + T_MINUS_EQUAL => 2, + T_POW_EQUAL => 3, + T_MOD_EQUAL => 2, + T_MUL_EQUAL => 2, + T_NAMESPACE => 9, + T_NS_C => 13, + T_NS_SEPARATOR => 1, + T_NEW => 3, + T_NULLSAFE_OBJECT_OPERATOR => 3, + T_OBJECT_OPERATOR => 2, + T_OPEN_TAG_WITH_ECHO => 3, + T_OR_EQUAL => 2, + T_PLUS_EQUAL => 2, + T_PRINT => 5, + T_PRIVATE => 7, + T_PUBLIC => 6, + T_PROTECTED => 9, + T_READONLY => 8, + T_REQUIRE => 7, + T_REQUIRE_ONCE => 12, + T_RETURN => 6, + T_STATIC => 6, + T_SWITCH => 6, + T_THROW => 5, + T_TRAIT => 5, + T_TRAIT_C => 9, + T_TRY => 3, + T_UNSET => 5, + T_USE => 3, + T_VAR => 3, + T_WHILE => 5, + T_XOR_EQUAL => 2, + T_YIELD => 5, + T_OPEN_CURLY_BRACKET => 1, + T_CLOSE_CURLY_BRACKET => 1, + T_OPEN_SQUARE_BRACKET => 1, + T_CLOSE_SQUARE_BRACKET => 1, + T_OPEN_PARENTHESIS => 1, + T_CLOSE_PARENTHESIS => 1, + T_COLON => 1, + T_STRING_CONCAT => 1, + T_INLINE_THEN => 1, + T_INLINE_ELSE => 1, + T_NULLABLE => 1, + T_NULL => 4, + T_FALSE => 5, + T_TRUE => 4, + T_SEMICOLON => 1, + T_EQUAL => 1, + T_MULTIPLY => 1, + T_DIVIDE => 1, + T_PLUS => 1, + T_MINUS => 1, + T_MODULUS => 1, + T_POW => 2, + T_SPACESHIP => 3, + T_COALESCE => 2, + T_COALESCE_EQUAL => 3, + T_BITWISE_AND => 1, + T_BITWISE_OR => 1, + T_BITWISE_XOR => 1, + T_SL => 2, + T_SR => 2, + T_SL_EQUAL => 3, + T_SR_EQUAL => 3, + T_GREATER_THAN => 1, + T_LESS_THAN => 1, + T_BOOLEAN_NOT => 1, + T_SELF => 4, + T_PARENT => 6, + T_COMMA => 1, + T_THIS => 4, + T_CLOSURE => 8, + T_BACKTICK => 1, + T_OPEN_SHORT_ARRAY => 1, + T_CLOSE_SHORT_ARRAY => 1, + T_TYPE_UNION => 1, + T_TYPE_INTERSECTION => 1, + ]; + + /** + * Contexts in which keywords should always be tokenized as T_STRING. + * + * @var array + */ + protected $tstringContexts = [ + T_OBJECT_OPERATOR => true, + T_NULLSAFE_OBJECT_OPERATOR => true, + T_FUNCTION => true, + T_CLASS => true, + T_INTERFACE => true, + T_TRAIT => true, + T_ENUM => true, + T_ENUM_CASE => true, + T_EXTENDS => true, + T_IMPLEMENTS => true, + T_ATTRIBUTE => true, + T_NEW => true, + T_CONST => true, + T_NS_SEPARATOR => true, + T_USE => true, + T_NAMESPACE => true, + T_PAAMAYIM_NEKUDOTAYIM => true, + ]; + + /** + * A cache of different token types, resolved into arrays. + * + * @var array + * @see standardiseToken() + */ + private static $resolveTokenCache = []; + + + /** + * Creates an array of tokens when given some PHP code. + * + * Starts by using token_get_all() but does a lot of extra processing + * to insert information about the context of the token. + * + * @param string $string The string to tokenize. + * + * @return array + */ + protected function tokenize($string) + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START PHP TOKENIZING ***".PHP_EOL; + $isWin = false; + if (stripos(PHP_OS, 'WIN') === 0) { + $isWin = true; + } + } + + $tokens = @token_get_all($string); + $finalTokens = []; + + $newStackPtr = 0; + $numTokens = count($tokens); + $lastNotEmptyToken = 0; + + $insideInlineIf = []; + $insideUseGroup = false; + + $commentTokenizer = new Comment(); + + for ($stackPtr = 0; $stackPtr < $numTokens; $stackPtr++) { + // Special case for tokens we have needed to blank out. + if ($tokens[$stackPtr] === null) { + continue; + } + + $token = (array) $tokens[$stackPtr]; + $tokenIsArray = isset($token[1]); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if ($tokenIsArray === true) { + $type = Util\Tokens::tokenName($token[0]); + $content = Util\Common::prepareForOutput($token[1]); + } else { + $newToken = self::resolveSimpleToken($token[0]); + $type = $newToken['type']; + $content = Util\Common::prepareForOutput($token[0]); + } + + echo "\tProcess token "; + if ($tokenIsArray === true) { + echo "[$stackPtr]"; + } else { + echo " $stackPtr "; + } + + echo ": $type => $content"; + }//end if + + if ($newStackPtr > 0 + && isset(Util\Tokens::$emptyTokens[$finalTokens[($newStackPtr - 1)]['code']]) === false + ) { + $lastNotEmptyToken = ($newStackPtr - 1); + } + + /* + If we are using \r\n newline characters, the \r and \n are sometimes + split over two tokens. This normally occurs after comments. We need + to merge these two characters together so that our line endings are + consistent for all lines. + */ + + if ($tokenIsArray === true && substr($token[1], -1) === "\r") { + if (isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][1][0] === "\n" + ) { + $token[1] .= "\n"; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + if ($isWin === true) { + echo '\n'; + } else { + echo "\033[30;1m\\n\033[0m"; + } + } + + if ($tokens[($stackPtr + 1)][1] === "\n") { + // This token's content has been merged into the previous, + // so we can skip it. + $tokens[($stackPtr + 1)] = ''; + } else { + $tokens[($stackPtr + 1)][1] = substr($tokens[($stackPtr + 1)][1], 1); + } + } + }//end if + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL; + } + + /* + Tokenize context sensitive keyword as string when it should be string. + */ + + if ($tokenIsArray === true + && isset(Util\Tokens::$contextSensitiveKeywords[$token[0]]) === true + && (isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === true + || $finalTokens[$lastNotEmptyToken]['content'] === '&') + ) { + if (isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === true) { + $preserveKeyword = false; + + // `new class`, and `new static` should be preserved. + if ($finalTokens[$lastNotEmptyToken]['code'] === T_NEW + && ($token[0] === T_CLASS + || $token[0] === T_STATIC) + ) { + $preserveKeyword = true; + } + + // `new class extends` `new class implements` should be preserved + if (($token[0] === T_EXTENDS || $token[0] === T_IMPLEMENTS) + && $finalTokens[$lastNotEmptyToken]['code'] === T_CLASS + ) { + $preserveKeyword = true; + } + + // `namespace\` should be preserved + if ($token[0] === T_NAMESPACE) { + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false) { + break; + } + + if (isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === true) { + continue; + } + + if ($tokens[$i][0] === T_NS_SEPARATOR) { + $preserveKeyword = true; + } + + break; + } + } + }//end if + + if ($finalTokens[$lastNotEmptyToken]['content'] === '&') { + $preserveKeyword = true; + + for ($i = ($lastNotEmptyToken - 1); $i >= 0; $i--) { + if (isset(Util\Tokens::$emptyTokens[$finalTokens[$i]['code']]) === true) { + continue; + } + + if ($finalTokens[$i]['code'] === T_FUNCTION) { + $preserveKeyword = false; + } + + break; + } + } + + if ($preserveKeyword === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = Util\Tokens::tokenName($token[0]); + echo "\t\t* token $stackPtr changed from $type to T_STRING".PHP_EOL; + } + + $finalTokens[$newStackPtr] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => $token[1], + ]; + + $newStackPtr++; + continue; + } + }//end if + + /* + Special case for `static` used as a function name, i.e. `static()`. + */ + + if ($tokenIsArray === true + && $token[0] === T_STATIC + && $finalTokens[$lastNotEmptyToken]['code'] !== T_NEW + ) { + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === true + && isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === true + ) { + continue; + } + + if ($tokens[$i][0] === '(') { + $finalTokens[$newStackPtr] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => $token[1], + ]; + + $newStackPtr++; + continue 2; + } + + break; + } + }//end if + + /* + Parse doc blocks into something that can be easily iterated over. + */ + + if ($tokenIsArray === true + && ($token[0] === T_DOC_COMMENT + || ($token[0] === T_COMMENT && strpos($token[1], '/**') === 0)) + ) { + $commentTokens = $commentTokenizer->tokenizeString($token[1], $this->eolChar, $newStackPtr); + foreach ($commentTokens as $commentToken) { + $finalTokens[$newStackPtr] = $commentToken; + $newStackPtr++; + } + + continue; + } + + /* + PHP 8 tokenizes a new line after a slash and hash comment to the next whitespace token. + */ + + if (PHP_VERSION_ID >= 80000 + && $tokenIsArray === true + && ($token[0] === T_COMMENT && (strpos($token[1], '//') === 0 || strpos($token[1], '#') === 0)) + && isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === T_WHITESPACE + ) { + $nextToken = $tokens[($stackPtr + 1)]; + + // If the next token is a single new line, merge it into the comment token + // and set to it up to be skipped. + if ($nextToken[1] === "\n" || $nextToken[1] === "\r\n" || $nextToken[1] === "\n\r") { + $token[1] .= $nextToken[1]; + $tokens[($stackPtr + 1)] = null; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* merged newline after comment into comment token $stackPtr".PHP_EOL; + } + } else { + // This may be a whitespace token consisting of multiple new lines. + if (strpos($nextToken[1], "\r\n") === 0) { + $token[1] .= "\r\n"; + $tokens[($stackPtr + 1)][1] = substr($nextToken[1], 2); + } else if (strpos($nextToken[1], "\n\r") === 0) { + $token[1] .= "\n\r"; + $tokens[($stackPtr + 1)][1] = substr($nextToken[1], 2); + } else if (strpos($nextToken[1], "\n") === 0) { + $token[1] .= "\n"; + $tokens[($stackPtr + 1)][1] = substr($nextToken[1], 1); + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* stripped first newline after comment and added it to comment token $stackPtr".PHP_EOL; + } + }//end if + }//end if + + /* + For Explicit Octal Notation prior to PHP 8.1 we need to combine the + T_LNUMBER and T_STRING token values into a single token value, and + then ignore the T_STRING token. + */ + + if (PHP_VERSION_ID < 80100 + && $tokenIsArray === true && $token[1] === '0' + && (isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === T_STRING + && isset($tokens[($stackPtr + 1)][1][0], $tokens[($stackPtr + 1)][1][1]) === true + && strtolower($tokens[($stackPtr + 1)][1][0]) === 'o' + && $tokens[($stackPtr + 1)][1][1] !== '_') + && preg_match('`^(o[0-7]+(?:_[0-7]+)?)([0-9_]*)$`i', $tokens[($stackPtr + 1)][1], $matches) === 1 + ) { + $finalTokens[$newStackPtr] = [ + 'code' => T_LNUMBER, + 'type' => 'T_LNUMBER', + 'content' => $token[1] .= $matches[1], + ]; + $newStackPtr++; + + if (isset($matches[2]) === true && $matches[2] !== '') { + $type = 'T_LNUMBER'; + if ($matches[2][0] === '_') { + $type = 'T_STRING'; + } + + $finalTokens[$newStackPtr] = [ + 'code' => constant($type), + 'type' => $type, + 'content' => $matches[2], + ]; + $newStackPtr++; + } + + $stackPtr++; + continue; + }//end if + + /* + PHP 8.1 introduced two dedicated tokens for the & character. + Retokenizing both of these to T_BITWISE_AND, which is the + token PHPCS already tokenized them as. + */ + + if ($tokenIsArray === true + && ($token[0] === T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG + || $token[0] === T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG) + ) { + $finalTokens[$newStackPtr] = [ + 'code' => T_BITWISE_AND, + 'type' => 'T_BITWISE_AND', + 'content' => $token[1], + ]; + $newStackPtr++; + continue; + } + + /* + If this is a double quoted string, PHP will tokenize the whole + thing which causes problems with the scope map when braces are + within the string. So we need to merge the tokens together to + provide a single string. + */ + + if ($tokenIsArray === false && ($token[0] === '"' || $token[0] === 'b"')) { + // Binary casts need a special token. + if ($token[0] === 'b"') { + $finalTokens[$newStackPtr] = [ + 'code' => T_BINARY_CAST, + 'type' => 'T_BINARY_CAST', + 'content' => 'b', + ]; + $newStackPtr++; + } + + $tokenContent = '"'; + $nestedVars = []; + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + $subToken = (array) $tokens[$i]; + $subTokenIsArray = isset($subToken[1]); + + if ($subTokenIsArray === true) { + $tokenContent .= $subToken[1]; + if (($subToken[1] === '{' + || $subToken[1] === '${') + && $subToken[0] !== T_ENCAPSED_AND_WHITESPACE + ) { + $nestedVars[] = $i; + } + } else { + $tokenContent .= $subToken[0]; + if ($subToken[0] === '}') { + array_pop($nestedVars); + } + } + + if ($subTokenIsArray === false + && $subToken[0] === '"' + && empty($nestedVars) === true + ) { + // We found the other end of the double quoted string. + break; + } + }//end for + + $stackPtr = $i; + + // Convert each line within the double quoted string to a + // new token, so it conforms with other multiple line tokens. + $tokenLines = explode($this->eolChar, $tokenContent); + $numLines = count($tokenLines); + $newToken = []; + + for ($j = 0; $j < $numLines; $j++) { + $newToken['content'] = $tokenLines[$j]; + if ($j === ($numLines - 1)) { + if ($tokenLines[$j] === '') { + break; + } + } else { + $newToken['content'] .= $this->eolChar; + } + + $newToken['code'] = T_DOUBLE_QUOTED_STRING; + $newToken['type'] = 'T_DOUBLE_QUOTED_STRING'; + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + } + + // Continue, as we're done with this token. + continue; + }//end if + + /* + Detect binary casting and assign the casts their own token. + */ + + if ($tokenIsArray === true + && $token[0] === T_CONSTANT_ENCAPSED_STRING + && (substr($token[1], 0, 2) === 'b"' + || substr($token[1], 0, 2) === "b'") + ) { + $finalTokens[$newStackPtr] = [ + 'code' => T_BINARY_CAST, + 'type' => 'T_BINARY_CAST', + 'content' => 'b', + ]; + $newStackPtr++; + $token[1] = substr($token[1], 1); + } + + if ($tokenIsArray === true + && $token[0] === T_STRING_CAST + && preg_match('`^\(\s*binary\s*\)$`i', $token[1]) === 1 + ) { + $finalTokens[$newStackPtr] = [ + 'code' => T_BINARY_CAST, + 'type' => 'T_BINARY_CAST', + 'content' => $token[1], + ]; + $newStackPtr++; + continue; + } + + /* + If this is a heredoc, PHP will tokenize the whole + thing which causes problems when heredocs don't + contain real PHP code, which is almost never. + We want to leave the start and end heredoc tokens + alone though. + */ + + if ($tokenIsArray === true && $token[0] === T_START_HEREDOC) { + // Add the start heredoc token to the final array. + $finalTokens[$newStackPtr] = self::standardiseToken($token); + + // Check if this is actually a nowdoc and use a different token + // to help the sniffs. + $nowdoc = false; + if (strpos($token[1], "'") !== false) { + $finalTokens[$newStackPtr]['code'] = T_START_NOWDOC; + $finalTokens[$newStackPtr]['type'] = 'T_START_NOWDOC'; + $nowdoc = true; + } + + $tokenContent = ''; + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + $subTokenIsArray = is_array($tokens[$i]); + if ($subTokenIsArray === true + && $tokens[$i][0] === T_END_HEREDOC + ) { + // We found the other end of the heredoc. + break; + } + + if ($subTokenIsArray === true) { + $tokenContent .= $tokens[$i][1]; + } else { + $tokenContent .= $tokens[$i]; + } + } + + if ($i === $numTokens) { + // We got to the end of the file and never + // found the closing token, so this probably wasn't + // a heredoc. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $finalTokens[$newStackPtr]['type']; + echo "\t\t* failed to find the end of the here/nowdoc".PHP_EOL; + echo "\t\t* token $stackPtr changed from $type to T_STRING".PHP_EOL; + } + + $finalTokens[$newStackPtr]['code'] = T_STRING; + $finalTokens[$newStackPtr]['type'] = 'T_STRING'; + $newStackPtr++; + continue; + } + + $stackPtr = $i; + $newStackPtr++; + + // Convert each line within the heredoc to a + // new token, so it conforms with other multiple line tokens. + $tokenLines = explode($this->eolChar, $tokenContent); + $numLines = count($tokenLines); + $newToken = []; + + for ($j = 0; $j < $numLines; $j++) { + $newToken['content'] = $tokenLines[$j]; + if ($j === ($numLines - 1)) { + if ($tokenLines[$j] === '') { + break; + } + } else { + $newToken['content'] .= $this->eolChar; + } + + if ($nowdoc === true) { + $newToken['code'] = T_NOWDOC; + $newToken['type'] = 'T_NOWDOC'; + } else { + $newToken['code'] = T_HEREDOC; + $newToken['type'] = 'T_HEREDOC'; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + }//end for + + // Add the end heredoc token to the final array. + $finalTokens[$newStackPtr] = self::standardiseToken($tokens[$stackPtr]); + + if ($nowdoc === true) { + $finalTokens[$newStackPtr]['code'] = T_END_NOWDOC; + $finalTokens[$newStackPtr]['type'] = 'T_END_NOWDOC'; + } + + $newStackPtr++; + + // Continue, as we're done with this token. + continue; + }//end if + + /* + Enum keyword for PHP < 8.1 + */ + + if ($tokenIsArray === true + && $token[0] === T_STRING + && strtolower($token[1]) === 'enum' + ) { + // Get the next non-empty token. + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === false + ) { + break; + } + } + + if (isset($tokens[$i]) === true + && is_array($tokens[$i]) === true + && $tokens[$i][0] === T_STRING + ) { + // Modify $tokens directly so we can use it later when converting enum "case". + $tokens[$stackPtr][0] = T_ENUM; + + $newToken = []; + $newToken['code'] = T_ENUM; + $newToken['type'] = 'T_ENUM'; + $newToken['content'] = $token[1]; + $finalTokens[$newStackPtr] = $newToken; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_STRING to T_ENUM".PHP_EOL; + } + + $newStackPtr++; + continue; + } + }//end if + + /* + Convert enum "case" to T_ENUM_CASE + */ + + if ($tokenIsArray === true + && $token[0] === T_CASE + && isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === false + ) { + $isEnumCase = false; + $scope = 1; + + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if ($tokens[$i] === '}') { + $scope++; + continue; + } + + if ($tokens[$i] === '{') { + $scope--; + continue; + } + + if (is_array($tokens[$i]) === false) { + continue; + } + + if ($scope !== 0) { + continue; + } + + if ($tokens[$i][0] === T_SWITCH) { + break; + } + + if ($tokens[$i][0] === T_ENUM || $tokens[$i][0] === T_ENUM_CASE) { + $isEnumCase = true; + break; + } + }//end for + + if ($isEnumCase === true) { + // Modify $tokens directly so we can use it as optimisation for other enum "case". + $tokens[$stackPtr][0] = T_ENUM_CASE; + + $newToken = []; + $newToken['code'] = T_ENUM_CASE; + $newToken['type'] = 'T_ENUM_CASE'; + $newToken['content'] = $token[1]; + $finalTokens[$newStackPtr] = $newToken; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_CASE to T_ENUM_CASE".PHP_EOL; + } + + $newStackPtr++; + continue; + } + }//end if + + /* + As of PHP 8.0 fully qualified, partially qualified and namespace relative + identifier names are tokenized differently. + This "undoes" the new tokenization so the tokenization will be the same in + in PHP 5, 7 and 8. + */ + + if (PHP_VERSION_ID >= 80000 + && $tokenIsArray === true + && ($token[0] === T_NAME_QUALIFIED + || $token[0] === T_NAME_FULLY_QUALIFIED + || $token[0] === T_NAME_RELATIVE) + ) { + $name = $token[1]; + + if ($token[0] === T_NAME_FULLY_QUALIFIED) { + $newToken = []; + $newToken['code'] = T_NS_SEPARATOR; + $newToken['type'] = 'T_NS_SEPARATOR'; + $newToken['content'] = '\\'; + $finalTokens[$newStackPtr] = $newToken; + ++$newStackPtr; + + $name = ltrim($name, '\\'); + } + + if ($token[0] === T_NAME_RELATIVE) { + $newToken = []; + $newToken['code'] = T_NAMESPACE; + $newToken['type'] = 'T_NAMESPACE'; + $newToken['content'] = substr($name, 0, 9); + $finalTokens[$newStackPtr] = $newToken; + ++$newStackPtr; + + $newToken = []; + $newToken['code'] = T_NS_SEPARATOR; + $newToken['type'] = 'T_NS_SEPARATOR'; + $newToken['content'] = '\\'; + $finalTokens[$newStackPtr] = $newToken; + ++$newStackPtr; + + $name = substr($name, 10); + } + + $parts = explode('\\', $name); + $partCount = count($parts); + $lastPart = ($partCount - 1); + + foreach ($parts as $i => $part) { + $newToken = []; + $newToken['code'] = T_STRING; + $newToken['type'] = 'T_STRING'; + $newToken['content'] = $part; + $finalTokens[$newStackPtr] = $newToken; + ++$newStackPtr; + + if ($i !== $lastPart) { + $newToken = []; + $newToken['code'] = T_NS_SEPARATOR; + $newToken['type'] = 'T_NS_SEPARATOR'; + $newToken['content'] = '\\'; + $finalTokens[$newStackPtr] = $newToken; + ++$newStackPtr; + } + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = Util\Tokens::tokenName($token[0]); + $content = Util\Common::prepareForOutput($token[1]); + echo "\t\t* token $stackPtr split into individual tokens; was: $type => $content".PHP_EOL; + } + + continue; + }//end if + + /* + PHP 8.0 Attributes + */ + + if (PHP_VERSION_ID < 80000 + && $token[0] === T_COMMENT + && strpos($token[1], '#[') === 0 + ) { + $subTokens = $this->parsePhpAttribute($tokens, $stackPtr); + if ($subTokens !== null) { + array_splice($tokens, $stackPtr, 1, $subTokens); + $numTokens = count($tokens); + + $tokenIsArray = true; + $token = $tokens[$stackPtr]; + } else { + $token[0] = T_ATTRIBUTE; + } + } + + if ($tokenIsArray === true + && $token[0] === T_ATTRIBUTE + ) { + // Go looking for the close bracket. + $bracketCloser = $this->findCloser($tokens, ($stackPtr + 1), ['[', '#['], ']'); + + $newToken = []; + $newToken['code'] = T_ATTRIBUTE; + $newToken['type'] = 'T_ATTRIBUTE'; + $newToken['content'] = '#['; + $finalTokens[$newStackPtr] = $newToken; + + $tokens[$bracketCloser] = []; + $tokens[$bracketCloser][0] = T_ATTRIBUTE_END; + $tokens[$bracketCloser][1] = ']'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $bracketCloser changed from T_CLOSE_SQUARE_BRACKET to T_ATTRIBUTE_END".PHP_EOL; + } + + $newStackPtr++; + continue; + }//end if + + /* + Tokenize the parameter labels for PHP 8.0 named parameters as a special T_PARAM_NAME + token and ensures that the colon after it is always T_COLON. + */ + + if ($tokenIsArray === true + && ($token[0] === T_STRING + || preg_match('`^[a-zA-Z_\x80-\xff]`', $token[1]) === 1) + ) { + // Get the next non-empty token. + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === false + ) { + break; + } + } + + if (isset($tokens[$i]) === true + && is_array($tokens[$i]) === false + && $tokens[$i] === ':' + ) { + // Get the previous non-empty token. + for ($j = ($stackPtr - 1); $j > 0; $j--) { + if (is_array($tokens[$j]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$j][0]]) === false + ) { + break; + } + } + + if (is_array($tokens[$j]) === false + && ($tokens[$j] === '(' + || $tokens[$j] === ',') + ) { + $newToken = []; + $newToken['code'] = T_PARAM_NAME; + $newToken['type'] = 'T_PARAM_NAME'; + $newToken['content'] = $token[1]; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + + // Modify the original token stack so that future checks, like + // determining T_COLON vs T_INLINE_ELSE can handle this correctly. + $tokens[$stackPtr][0] = T_PARAM_NAME; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = Util\Tokens::tokenName($token[0]); + echo "\t\t* token $stackPtr changed from $type to T_PARAM_NAME".PHP_EOL; + } + + continue; + } + }//end if + }//end if + + /* + "readonly" keyword for PHP < 8.1 + */ + + if ($tokenIsArray === true + && strtolower($token[1]) === 'readonly' + && isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === false + ) { + // Get the next non-whitespace token. + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === false + ) { + break; + } + } + + $isReadonlyKeyword = false; + + if (isset($tokens[$i]) === false + || $tokens[$i] !== '(' + ) { + $isReadonlyKeyword = true; + } else if ($tokens[$i] === '(') { + /* + * Skip over tokens which can be used in type declarations. + * At this point, the only token types which need to be taken into consideration + * as potential type declarations are identifier names, T_ARRAY, T_CALLABLE and T_NS_SEPARATOR + * and the union/intersection/dnf parentheses. + */ + + $foundDNFParens = 1; + $foundDNFPipe = 0; + + for (++$i; $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === true) { + $tokenType = $tokens[$i][0]; + } else { + $tokenType = $tokens[$i]; + } + + if (isset(Util\Tokens::$emptyTokens[$tokenType]) === true) { + continue; + } + + if ($tokenType === '|') { + ++$foundDNFPipe; + continue; + } + + if ($tokenType === ')') { + ++$foundDNFParens; + continue; + } + + if ($tokenType === '(') { + ++$foundDNFParens; + continue; + } + + if ($tokenType === T_STRING + || $tokenType === T_NAME_FULLY_QUALIFIED + || $tokenType === T_NAME_RELATIVE + || $tokenType === T_NAME_QUALIFIED + || $tokenType === T_ARRAY + || $tokenType === T_NAMESPACE + || $tokenType === T_NS_SEPARATOR + || $tokenType === T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG // PHP 8.0+. + || $tokenType === '&' // PHP < 8.0. + ) { + continue; + } + + // Reached the next token after. + if (($foundDNFParens % 2) === 0 + && $foundDNFPipe >= 1 + && ($tokenType === T_VARIABLE + || $tokenType === T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG) + ) { + $isReadonlyKeyword = true; + } + + break; + }//end for + }//end if + + if ($isReadonlyKeyword === true) { + $finalTokens[$newStackPtr] = [ + 'code' => T_READONLY, + 'type' => 'T_READONLY', + 'content' => $token[1], + ]; + $newStackPtr++; + + if (PHP_CODESNIFFER_VERBOSITY > 1 && $type !== T_READONLY) { + echo "\t\t* token $stackPtr changed from $type to T_READONLY".PHP_EOL; + } + } else { + $finalTokens[$newStackPtr] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => $token[1], + ]; + $newStackPtr++; + + if (PHP_CODESNIFFER_VERBOSITY > 1 && $type !== T_STRING) { + echo "\t\t* token $stackPtr changed from $type to T_STRING".PHP_EOL; + } + }//end if + + continue; + }//end if + + /* + Before PHP 7.0, the "yield from" was tokenized as + T_YIELD, T_WHITESPACE and T_STRING. So look for + and change this token in earlier versions. + */ + + if (PHP_VERSION_ID < 70000 + && PHP_VERSION_ID >= 50500 + && $tokenIsArray === true + && $token[0] === T_YIELD + && isset($tokens[($stackPtr + 1)]) === true + && isset($tokens[($stackPtr + 2)]) === true + && $tokens[($stackPtr + 1)][0] === T_WHITESPACE + && $tokens[($stackPtr + 2)][0] === T_STRING + && strtolower($tokens[($stackPtr + 2)][1]) === 'from' + ) { + // Could be multi-line, so adjust the token stack. + $token[0] = T_YIELD_FROM; + $token[1] .= $tokens[($stackPtr + 1)][1].$tokens[($stackPtr + 2)][1]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + for ($i = ($stackPtr + 1); $i <= ($stackPtr + 2); $i++) { + $type = Util\Tokens::tokenName($tokens[$i][0]); + $content = Util\Common::prepareForOutput($tokens[$i][1]); + echo "\t\t* token $i merged into T_YIELD_FROM; was: $type => $content".PHP_EOL; + } + } + + $tokens[($stackPtr + 1)] = null; + $tokens[($stackPtr + 2)] = null; + } + + /* + Before PHP 5.5, the yield keyword was tokenized as + T_STRING. So look for and change this token in + earlier versions. + Checks also if it is just "yield" or "yield from". + */ + + if (PHP_VERSION_ID < 50500 + && $tokenIsArray === true + && $token[0] === T_STRING + && strtolower($token[1]) === 'yield' + && isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === false + ) { + if (isset($tokens[($stackPtr + 1)]) === true + && isset($tokens[($stackPtr + 2)]) === true + && $tokens[($stackPtr + 1)][0] === T_WHITESPACE + && $tokens[($stackPtr + 2)][0] === T_STRING + && strtolower($tokens[($stackPtr + 2)][1]) === 'from' + ) { + // Could be multi-line, so just just the token stack. + $token[0] = T_YIELD_FROM; + $token[1] .= $tokens[($stackPtr + 1)][1].$tokens[($stackPtr + 2)][1]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + for ($i = ($stackPtr + 1); $i <= ($stackPtr + 2); $i++) { + $type = Util\Tokens::tokenName($tokens[$i][0]); + $content = Util\Common::prepareForOutput($tokens[$i][1]); + echo "\t\t* token $i merged into T_YIELD_FROM; was: $type => $content".PHP_EOL; + } + } + + $tokens[($stackPtr + 1)] = null; + $tokens[($stackPtr + 2)] = null; + } else { + $newToken = []; + $newToken['code'] = T_YIELD; + $newToken['type'] = 'T_YIELD'; + $newToken['content'] = $token[1]; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + continue; + }//end if + }//end if + + /* + Before PHP 5.6, the ... operator was tokenized as three + T_STRING_CONCAT tokens in a row. So look for and combine + these tokens in earlier versions. + */ + + if ($tokenIsArray === false + && $token[0] === '.' + && isset($tokens[($stackPtr + 1)]) === true + && isset($tokens[($stackPtr + 2)]) === true + && $tokens[($stackPtr + 1)] === '.' + && $tokens[($stackPtr + 2)] === '.' + ) { + $newToken = []; + $newToken['code'] = T_ELLIPSIS; + $newToken['type'] = 'T_ELLIPSIS'; + $newToken['content'] = '...'; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr += 2; + continue; + } + + /* + Before PHP 5.6, the ** operator was tokenized as two + T_MULTIPLY tokens in a row. So look for and combine + these tokens in earlier versions. + */ + + if ($tokenIsArray === false + && $token[0] === '*' + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)] === '*' + ) { + $newToken = []; + $newToken['code'] = T_POW; + $newToken['type'] = 'T_POW'; + $newToken['content'] = '**'; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + continue; + } + + /* + Before PHP 5.6, the **= operator was tokenized as + T_MULTIPLY followed by T_MUL_EQUAL. So look for and combine + these tokens in earlier versions. + */ + + if ($tokenIsArray === false + && $token[0] === '*' + && isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][1] === '*=' + ) { + $newToken = []; + $newToken['code'] = T_POW_EQUAL; + $newToken['type'] = 'T_POW_EQUAL'; + $newToken['content'] = '**='; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + continue; + } + + /* + Before PHP 7, the ??= operator was tokenized as + T_INLINE_THEN, T_INLINE_THEN, T_EQUAL. + Between PHP 7.0 and 7.3, the ??= operator was tokenized as + T_COALESCE, T_EQUAL. + So look for and combine these tokens in earlier versions. + */ + + if (($tokenIsArray === false + && $token[0] === '?' + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === '?' + && isset($tokens[($stackPtr + 2)]) === true + && $tokens[($stackPtr + 2)][0] === '=') + || ($tokenIsArray === true + && $token[0] === T_COALESCE + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === '=') + ) { + $newToken = []; + $newToken['code'] = T_COALESCE_EQUAL; + $newToken['type'] = 'T_COALESCE_EQUAL'; + $newToken['content'] = '??='; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + + if ($tokenIsArray === false) { + // Pre PHP 7. + $stackPtr++; + } + + continue; + } + + /* + Before PHP 7, the ?? operator was tokenized as + T_INLINE_THEN followed by T_INLINE_THEN. + So look for and combine these tokens in earlier versions. + */ + + if ($tokenIsArray === false + && $token[0] === '?' + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === '?' + ) { + $newToken = []; + $newToken['code'] = T_COALESCE; + $newToken['type'] = 'T_COALESCE'; + $newToken['content'] = '??'; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + continue; + } + + /* + Before PHP 8, the ?-> operator was tokenized as + T_INLINE_THEN followed by T_OBJECT_OPERATOR. + So look for and combine these tokens in earlier versions. + */ + + if ($tokenIsArray === false + && $token[0] === '?' + && isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === T_OBJECT_OPERATOR + ) { + $newToken = []; + $newToken['code'] = T_NULLSAFE_OBJECT_OPERATOR; + $newToken['type'] = 'T_NULLSAFE_OBJECT_OPERATOR'; + $newToken['content'] = '?->'; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + continue; + } + + /* + Before PHP 7.4, underscores inside T_LNUMBER and T_DNUMBER + tokens split the token with a T_STRING. So look for + and change these tokens in earlier versions. + */ + + if (PHP_VERSION_ID < 70400 + && ($tokenIsArray === true + && ($token[0] === T_LNUMBER + || $token[0] === T_DNUMBER) + && isset($tokens[($stackPtr + 1)]) === true + && is_array($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === T_STRING + && $tokens[($stackPtr + 1)][1][0] === '_') + ) { + $newContent = $token[1]; + $newType = $token[0]; + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false) { + break; + } + + if ($tokens[$i][0] === T_LNUMBER + || $tokens[$i][0] === T_DNUMBER + ) { + $newContent .= $tokens[$i][1]; + continue; + } + + if ($tokens[$i][0] === T_STRING + && $tokens[$i][1][0] === '_' + && ((strpos($newContent, '0x') === 0 + && preg_match('`^((? PHP_INT_MAX) + || (stripos($newContent, '0b') === 0 && bindec(str_replace('_', '', $newContent)) > PHP_INT_MAX) + || (stripos($newContent, '0o') === 0 && octdec(str_replace('_', '', $newContent)) > PHP_INT_MAX) + || (stripos($newContent, '0x') !== 0 + && stripos($newContent, 'e') !== false || strpos($newContent, '.') !== false) + || (strpos($newContent, '0') === 0 && stripos($newContent, '0x') !== 0 + && stripos($newContent, '0b') !== 0 && octdec(str_replace('_', '', $newContent)) > PHP_INT_MAX) + || (strpos($newContent, '0') !== 0 && str_replace('_', '', $newContent) > PHP_INT_MAX)) + ) { + $newType = T_DNUMBER; + } + + $newToken = []; + $newToken['code'] = $newType; + $newToken['type'] = Util\Tokens::tokenName($newType); + $newToken['content'] = $newContent; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr = ($i - 1); + continue; + }//end if + + /* + Backfill the T_MATCH token for PHP versions < 8.0 and + do initial correction for non-match expression T_MATCH tokens + to T_STRING for PHP >= 8.0. + A final check for non-match expression T_MATCH tokens is done + in PHP::processAdditional(). + */ + + if ($tokenIsArray === true + && (($token[0] === T_STRING + && strtolower($token[1]) === 'match') + || $token[0] === T_MATCH) + ) { + $isMatch = false; + for ($x = ($stackPtr + 1); $x < $numTokens; $x++) { + if (isset($tokens[$x][0], Util\Tokens::$emptyTokens[$tokens[$x][0]]) === true) { + continue; + } + + if ($tokens[$x] !== '(') { + // This is not a match expression. + break; + } + + if (isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === true) { + // Also not a match expression. + break; + } + + $isMatch = true; + break; + }//end for + + if ($isMatch === true && $token[0] === T_STRING) { + $newToken = []; + $newToken['code'] = T_MATCH; + $newToken['type'] = 'T_MATCH'; + $newToken['content'] = $token[1]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_STRING to T_MATCH".PHP_EOL; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + continue; + } else if ($isMatch === false && $token[0] === T_MATCH) { + // PHP 8.0, match keyword, but not a match expression. + $newToken = []; + $newToken['code'] = T_STRING; + $newToken['type'] = 'T_STRING'; + $newToken['content'] = $token[1]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_MATCH to T_STRING".PHP_EOL; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + continue; + }//end if + }//end if + + /* + Retokenize the T_DEFAULT in match control structures as T_MATCH_DEFAULT + to prevent scope being set and the scope for switch default statements + breaking. + */ + + if ($tokenIsArray === true + && $token[0] === T_DEFAULT + && isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === false + ) { + for ($x = ($stackPtr + 1); $x < $numTokens; $x++) { + if ($tokens[$x] === ',') { + // Skip over potential trailing comma (supported in PHP). + continue; + } + + if (is_array($tokens[$x]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$x][0]]) === false + ) { + // Non-empty, non-comma content. + break; + } + } + + if (isset($tokens[$x]) === true + && is_array($tokens[$x]) === true + && $tokens[$x][0] === T_DOUBLE_ARROW + ) { + // Modify the original token stack for the double arrow so that + // future checks can disregard the double arrow token more easily. + // For match expression "case" statements, this is handled + // in PHP::processAdditional(). + $tokens[$x][0] = T_MATCH_ARROW; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $x changed from T_DOUBLE_ARROW to T_MATCH_ARROW".PHP_EOL; + } + + $newToken = []; + $newToken['code'] = T_MATCH_DEFAULT; + $newToken['type'] = 'T_MATCH_DEFAULT'; + $newToken['content'] = $token[1]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_DEFAULT to T_MATCH_DEFAULT".PHP_EOL; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + continue; + }//end if + }//end if + + /* + Convert ? to T_NULLABLE OR T_INLINE_THEN + */ + + if ($tokenIsArray === false && $token[0] === '?') { + $newToken = []; + $newToken['content'] = '?'; + + /* + * Check if the next non-empty token is one of the tokens which can be used + * in type declarations. If not, it's definitely a ternary. + * At this point, the only token types which need to be taken into consideration + * as potential type declarations are identifier names, T_ARRAY, T_CALLABLE and T_NS_SEPARATOR. + */ + + $lastRelevantNonEmpty = null; + + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === true) { + $tokenType = $tokens[$i][0]; + } else { + $tokenType = $tokens[$i]; + } + + if (isset(Util\Tokens::$emptyTokens[$tokenType]) === true) { + continue; + } + + if ($tokenType === T_STRING + || $tokenType === T_NAME_FULLY_QUALIFIED + || $tokenType === T_NAME_RELATIVE + || $tokenType === T_NAME_QUALIFIED + || $tokenType === T_ARRAY + || $tokenType === T_NAMESPACE + || $tokenType === T_NS_SEPARATOR + ) { + $lastRelevantNonEmpty = $tokenType; + continue; + } + + if (($tokenType !== T_CALLABLE + && isset($lastRelevantNonEmpty) === false) + || ($lastRelevantNonEmpty === T_ARRAY + && $tokenType === '(') + || (($lastRelevantNonEmpty === T_STRING + || $lastRelevantNonEmpty === T_NAME_FULLY_QUALIFIED + || $lastRelevantNonEmpty === T_NAME_RELATIVE + || $lastRelevantNonEmpty === T_NAME_QUALIFIED) + && ($tokenType === T_DOUBLE_COLON + || $tokenType === '(' + || $tokenType === ':')) + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from ? to T_INLINE_THEN".PHP_EOL; + } + + $newToken['code'] = T_INLINE_THEN; + $newToken['type'] = 'T_INLINE_THEN'; + + $insideInlineIf[] = $stackPtr; + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + continue 2; + } + + break; + }//end for + + /* + * This can still be a nullable type or a ternary. + * Do additional checking. + */ + + $prevNonEmpty = null; + $lastSeenNonEmpty = null; + + for ($i = ($stackPtr - 1); $i >= 0; $i--) { + if (is_array($tokens[$i]) === true) { + $tokenType = $tokens[$i][0]; + } else { + $tokenType = $tokens[$i]; + } + + if ($tokenType === T_STATIC + && ($lastSeenNonEmpty === T_DOUBLE_COLON + || $lastSeenNonEmpty === '(') + ) { + $lastSeenNonEmpty = $tokenType; + continue; + } + + if ($prevNonEmpty === null + && isset(Util\Tokens::$emptyTokens[$tokenType]) === false + ) { + // Found the previous non-empty token. + if ($tokenType === ':' || $tokenType === ',' || $tokenType === T_ATTRIBUTE_END) { + $newToken['code'] = T_NULLABLE; + $newToken['type'] = 'T_NULLABLE'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from ? to T_NULLABLE".PHP_EOL; + } + + break; + } + + $prevNonEmpty = $tokenType; + } + + if ($tokenType === T_FUNCTION + || $tokenType === T_FN + || isset(Util\Tokens::$methodPrefixes[$tokenType]) === true + || $tokenType === T_VAR + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from ? to T_NULLABLE".PHP_EOL; + } + + $newToken['code'] = T_NULLABLE; + $newToken['type'] = 'T_NULLABLE'; + break; + } else if (in_array($tokenType, [T_DOUBLE_ARROW, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, '=', '{', ';'], true) === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from ? to T_INLINE_THEN".PHP_EOL; + } + + $newToken['code'] = T_INLINE_THEN; + $newToken['type'] = 'T_INLINE_THEN'; + + $insideInlineIf[] = $stackPtr; + break; + } + + if (isset(Util\Tokens::$emptyTokens[$tokenType]) === false) { + $lastSeenNonEmpty = $tokenType; + } + }//end for + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + continue; + }//end if + + /* + Tokens after a double colon may look like scope openers, + such as when writing code like Foo::NAMESPACE, but they are + only ever variables or strings. + */ + + if ($stackPtr > 1 + && (is_array($tokens[($stackPtr - 1)]) === true + && $tokens[($stackPtr - 1)][0] === T_PAAMAYIM_NEKUDOTAYIM) + && $tokenIsArray === true + && $token[0] !== T_STRING + && $token[0] !== T_VARIABLE + && $token[0] !== T_DOLLAR + && isset(Util\Tokens::$emptyTokens[$token[0]]) === false + ) { + $newToken = []; + $newToken['code'] = T_STRING; + $newToken['type'] = 'T_STRING'; + $newToken['content'] = $token[1]; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + continue; + } + + /* + Backfill the T_FN token for PHP versions < 7.4. + */ + + if ($tokenIsArray === true + && $token[0] === T_STRING + && strtolower($token[1]) === 'fn' + ) { + // Modify the original token stack so that + // future checks (like looking for T_NULLABLE) can + // detect the T_FN token more easily. + $tokens[$stackPtr][0] = T_FN; + $token[0] = T_FN; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_STRING to T_FN".PHP_EOL; + } + } + + /* + This is a special condition for T_ARRAY tokens used for + function return types. We want to keep the parenthesis map clean, + so let's tag these tokens as T_STRING. + */ + + if ($tokenIsArray === true + && ($token[0] === T_FUNCTION + || $token[0] === T_FN) + && $finalTokens[$lastNotEmptyToken]['code'] !== T_USE + ) { + // Go looking for the colon to start the return type hint. + // Start by finding the closing parenthesis of the function. + $parenthesisStack = []; + $parenthesisCloser = false; + for ($x = ($stackPtr + 1); $x < $numTokens; $x++) { + if (is_array($tokens[$x]) === false && $tokens[$x] === '(') { + $parenthesisStack[] = $x; + } else if (is_array($tokens[$x]) === false && $tokens[$x] === ')') { + array_pop($parenthesisStack); + if (empty($parenthesisStack) === true) { + $parenthesisCloser = $x; + break; + } + } + } + + if ($parenthesisCloser !== false) { + for ($x = ($parenthesisCloser + 1); $x < $numTokens; $x++) { + if (is_array($tokens[$x]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$x][0]]) === false + ) { + // Non-empty content. + if (is_array($tokens[$x]) === true && $tokens[$x][0] === T_USE) { + // Found a use statements, so search ahead for the closing parenthesis. + for ($x += 1; $x < $numTokens; $x++) { + if (is_array($tokens[$x]) === false && $tokens[$x] === ')') { + continue(2); + } + } + } + + break; + } + } + + if (isset($tokens[$x]) === true + && is_array($tokens[$x]) === false + && $tokens[$x] === ':' + ) { + // Find the start of the return type. + for ($x += 1; $x < $numTokens; $x++) { + if (is_array($tokens[$x]) === true + && isset(Util\Tokens::$emptyTokens[$tokens[$x][0]]) === true + ) { + // Whitespace or comments before the return type. + continue; + } + + if (is_array($tokens[$x]) === false && $tokens[$x] === '?') { + // Found a nullable operator, so skip it. + // But also convert the token to save the tokenizer + // a bit of time later on. + $tokens[$x] = [ + T_NULLABLE, + '?', + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $x changed from ? to T_NULLABLE".PHP_EOL; + } + + continue; + } + + break; + }//end for + }//end if + }//end if + }//end if + + /* + Before PHP 7, the <=> operator was tokenized as + T_IS_SMALLER_OR_EQUAL followed by T_GREATER_THAN. + So look for and combine these tokens in earlier versions. + */ + + if ($tokenIsArray === true + && $token[0] === T_IS_SMALLER_OR_EQUAL + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)][0] === '>' + ) { + $newToken = []; + $newToken['code'] = T_SPACESHIP; + $newToken['type'] = 'T_SPACESHIP'; + $newToken['content'] = '<=>'; + $finalTokens[$newStackPtr] = $newToken; + + $newStackPtr++; + $stackPtr++; + continue; + } + + /* + PHP doesn't assign a token to goto labels, so we have to. + These are just string tokens with a single colon after them. Double + colons are already tokenized and so don't interfere with this check. + But we do have to account for CASE statements, that look just like + goto labels. + */ + + if ($tokenIsArray === true + && $token[0] === T_STRING + && isset($tokens[($stackPtr + 1)]) === true + && $tokens[($stackPtr + 1)] === ':' + && (is_array($tokens[($stackPtr - 1)]) === false + || $tokens[($stackPtr - 1)][0] !== T_PAAMAYIM_NEKUDOTAYIM) + ) { + $stopTokens = [ + T_CASE => true, + T_SEMICOLON => true, + T_OPEN_TAG => true, + T_OPEN_CURLY_BRACKET => true, + T_INLINE_THEN => true, + T_ENUM => true, + ]; + + for ($x = ($newStackPtr - 1); $x > 0; $x--) { + if (isset($stopTokens[$finalTokens[$x]['code']]) === true) { + break; + } + } + + if ($finalTokens[$x]['code'] !== T_CASE + && $finalTokens[$x]['code'] !== T_INLINE_THEN + && $finalTokens[$x]['code'] !== T_ENUM + ) { + $finalTokens[$newStackPtr] = [ + 'content' => $token[1].':', + 'code' => T_GOTO_LABEL, + 'type' => 'T_GOTO_LABEL', + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $stackPtr changed from T_STRING to T_GOTO_LABEL".PHP_EOL; + echo "\t\t* skipping T_COLON token ".($stackPtr + 1).PHP_EOL; + } + + $newStackPtr++; + $stackPtr++; + continue; + } + }//end if + + /* + If this token has newlines in its content, split each line up + and create a new token for each line. We do this so it's easier + to ascertain where errors occur on a line. + Note that $token[1] is the token's content. + */ + + if ($tokenIsArray === true && strpos($token[1], $this->eolChar) !== false) { + $tokenLines = explode($this->eolChar, $token[1]); + $numLines = count($tokenLines); + $newToken = [ + 'type' => Util\Tokens::tokenName($token[0]), + 'code' => $token[0], + 'content' => '', + ]; + + for ($i = 0; $i < $numLines; $i++) { + $newToken['content'] = $tokenLines[$i]; + if ($i === ($numLines - 1)) { + if ($tokenLines[$i] === '') { + break; + } + } else { + $newToken['content'] .= $this->eolChar; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + } + } else { + // Some T_STRING tokens should remain that way due to their context. + if ($tokenIsArray === true && $token[0] === T_STRING) { + $preserveTstring = false; + + if (isset($this->tstringContexts[$finalTokens[$lastNotEmptyToken]['code']]) === true) { + $preserveTstring = true; + + // Special case for syntax like: return new self/new parent + // where self/parent should not be a string. + $tokenContentLower = strtolower($token[1]); + if ($finalTokens[$lastNotEmptyToken]['code'] === T_NEW + && ($tokenContentLower === 'self' || $tokenContentLower === 'parent') + ) { + $preserveTstring = false; + } + } else if ($finalTokens[$lastNotEmptyToken]['content'] === '&') { + // Function names for functions declared to return by reference. + for ($i = ($lastNotEmptyToken - 1); $i >= 0; $i--) { + if (isset(Util\Tokens::$emptyTokens[$finalTokens[$i]['code']]) === true) { + continue; + } + + if ($finalTokens[$i]['code'] === T_FUNCTION) { + $preserveTstring = true; + } + + break; + } + } else { + // Keywords with special PHPCS token when used as a function call. + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === true + && isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === true + ) { + continue; + } + + if ($tokens[$i][0] === '(') { + $preserveTstring = true; + } + + break; + } + }//end if + + if ($preserveTstring === true) { + $finalTokens[$newStackPtr] = [ + 'code' => T_STRING, + 'type' => 'T_STRING', + 'content' => $token[1], + ]; + + $newStackPtr++; + continue; + } + }//end if + + $newToken = null; + if ($tokenIsArray === false) { + if (isset(self::$resolveTokenCache[$token[0]]) === true) { + $newToken = self::$resolveTokenCache[$token[0]]; + } + } else { + $cacheKey = null; + if ($token[0] === T_STRING) { + $cacheKey = strtolower($token[1]); + } else if ($token[0] !== T_CURLY_OPEN) { + $cacheKey = $token[0]; + } + + if ($cacheKey !== null && isset(self::$resolveTokenCache[$cacheKey]) === true) { + $newToken = self::$resolveTokenCache[$cacheKey]; + $newToken['content'] = $token[1]; + } + } + + if ($newToken === null) { + $newToken = self::standardiseToken($token); + } + + // Convert colons that are actually the ELSE component of an + // inline IF statement. + if (empty($insideInlineIf) === false && $newToken['code'] === T_COLON) { + $isInlineIf = true; + + // Make sure this isn't a named parameter label. + // Get the previous non-empty token. + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if (is_array($tokens[$i]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === false + ) { + break; + } + } + + if ($tokens[$i][0] === T_PARAM_NAME) { + $isInlineIf = false; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is parameter label, not T_INLINE_ELSE".PHP_EOL; + } + } + + if ($isInlineIf === true) { + // Make sure this isn't a return type separator. + for ($i = ($stackPtr - 1); $i > 0; $i--) { + if (is_array($tokens[$i]) === false + || ($tokens[$i][0] !== T_DOC_COMMENT + && $tokens[$i][0] !== T_COMMENT + && $tokens[$i][0] !== T_WHITESPACE) + ) { + break; + } + } + + if ($tokens[$i] === ')') { + $parenCount = 1; + for ($i--; $i > 0; $i--) { + if ($tokens[$i] === '(') { + $parenCount--; + if ($parenCount === 0) { + break; + } + } else if ($tokens[$i] === ')') { + $parenCount++; + } + } + + // We've found the open parenthesis, so if the previous + // non-empty token is FUNCTION or USE, this is a return type. + // Note that we need to skip T_STRING tokens here as these + // can be function names. + for ($i--; $i > 0; $i--) { + if (is_array($tokens[$i]) === false + || ($tokens[$i][0] !== T_DOC_COMMENT + && $tokens[$i][0] !== T_COMMENT + && $tokens[$i][0] !== T_WHITESPACE + && $tokens[$i][0] !== T_STRING) + ) { + break; + } + } + + if ($tokens[$i][0] === T_FUNCTION || $tokens[$i][0] === T_FN || $tokens[$i][0] === T_USE) { + $isInlineIf = false; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is return type, not T_INLINE_ELSE".PHP_EOL; + } + } + }//end if + }//end if + + // Check to see if this is a CASE or DEFAULT opener. + if ($isInlineIf === true) { + $inlineIfToken = $insideInlineIf[(count($insideInlineIf) - 1)]; + for ($i = $stackPtr; $i > $inlineIfToken; $i--) { + if (is_array($tokens[$i]) === true + && ($tokens[$i][0] === T_CASE + || $tokens[$i][0] === T_DEFAULT) + ) { + $isInlineIf = false; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token is T_CASE or T_DEFAULT opener, not T_INLINE_ELSE".PHP_EOL; + } + + break; + } + + if (is_array($tokens[$i]) === false + && ($tokens[$i] === ';' + || $tokens[$i] === '{' + || $tokens[$i] === '}') + ) { + break; + } + }//end for + }//end if + + if ($isInlineIf === true) { + array_pop($insideInlineIf); + $newToken['code'] = T_INLINE_ELSE; + $newToken['type'] = 'T_INLINE_ELSE'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token changed from T_COLON to T_INLINE_ELSE".PHP_EOL; + } + } + }//end if + + // This is a special condition for T_ARRAY tokens used for anything else + // but array declarations, like type hinting function arguments as + // being arrays. + // We want to keep the parenthesis map clean, so let's tag these tokens as + // T_STRING. + if ($newToken['code'] === T_ARRAY) { + for ($i = ($stackPtr + 1); $i < $numTokens; $i++) { + if (is_array($tokens[$i]) === false + || isset(Util\Tokens::$emptyTokens[$tokens[$i][0]]) === false + ) { + // Non-empty content. + break; + } + } + + if ($i !== $numTokens && $tokens[$i] !== '(') { + $newToken['code'] = T_STRING; + $newToken['type'] = 'T_STRING'; + } + } + + // This is a special case when checking PHP 5.5+ code in PHP < 5.5 + // where "finally" should be T_FINALLY instead of T_STRING. + if ($newToken['code'] === T_STRING + && strtolower($newToken['content']) === 'finally' + && $finalTokens[$lastNotEmptyToken]['code'] === T_CLOSE_CURLY_BRACKET + ) { + $newToken['code'] = T_FINALLY; + $newToken['type'] = 'T_FINALLY'; + } + + // This is a special case for PHP 5.6 use function and use const + // where "function" and "const" should be T_STRING instead of T_FUNCTION + // and T_CONST. + if (($newToken['code'] === T_FUNCTION + || $newToken['code'] === T_CONST) + && ($finalTokens[$lastNotEmptyToken]['code'] === T_USE || $insideUseGroup === true) + ) { + $newToken['code'] = T_STRING; + $newToken['type'] = 'T_STRING'; + } + + // This is a special case for use groups in PHP 7+ where leaving + // the curly braces as their normal tokens would confuse + // the scope map and sniffs. + if ($newToken['code'] === T_OPEN_CURLY_BRACKET + && $finalTokens[$lastNotEmptyToken]['code'] === T_NS_SEPARATOR + ) { + $newToken['code'] = T_OPEN_USE_GROUP; + $newToken['type'] = 'T_OPEN_USE_GROUP'; + $insideUseGroup = true; + } + + if ($insideUseGroup === true && $newToken['code'] === T_CLOSE_CURLY_BRACKET) { + $newToken['code'] = T_CLOSE_USE_GROUP; + $newToken['type'] = 'T_CLOSE_USE_GROUP'; + $insideUseGroup = false; + } + + $finalTokens[$newStackPtr] = $newToken; + $newStackPtr++; + }//end if + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END PHP TOKENIZING ***".PHP_EOL; + } + + return $finalTokens; + + }//end tokenize() + + + /** + * Performs additional processing after main tokenizing. + * + * This additional processing checks for CASE statements that are using curly + * braces for scope openers and closers. It also turns some T_FUNCTION tokens + * into T_CLOSURE when they are not standard function definitions. It also + * detects short array syntax and converts those square brackets into new tokens. + * It also corrects some usage of the static and class keywords. It also + * assigns tokens to function return types. + * + * @return void + */ + protected function processAdditional() + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START ADDITIONAL PHP PROCESSING ***".PHP_EOL; + } + + $this->createAttributesNestingMap(); + + $numTokens = count($this->tokens); + for ($i = ($numTokens - 1); $i >= 0; $i--) { + // Check for any unset scope conditions due to alternate IF/ENDIF syntax. + if (isset($this->tokens[$i]['scope_opener']) === true + && isset($this->tokens[$i]['scope_condition']) === false + ) { + $this->tokens[$i]['scope_condition'] = $this->tokens[$this->tokens[$i]['scope_opener']]['scope_condition']; + } + + if ($this->tokens[$i]['code'] === T_FUNCTION) { + /* + Detect functions that are actually closures and + assign them a different token. + */ + + if (isset($this->tokens[$i]['scope_opener']) === true) { + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false + && $this->tokens[$x]['code'] !== T_BITWISE_AND + ) { + break; + } + } + + if ($this->tokens[$x]['code'] === T_OPEN_PARENTHESIS) { + $this->tokens[$i]['code'] = T_CLOSURE; + $this->tokens[$i]['type'] = 'T_CLOSURE'; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t* token $i on line $line changed from T_FUNCTION to T_CLOSURE".PHP_EOL; + } + + for ($x = ($this->tokens[$i]['scope_opener'] + 1); $x < $this->tokens[$i]['scope_closer']; $x++) { + if (isset($this->tokens[$x]['conditions'][$i]) === false) { + continue; + } + + $this->tokens[$x]['conditions'][$i] = T_CLOSURE; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + echo "\t\t* cleaned $x ($type) *".PHP_EOL; + } + } + } + }//end if + + continue; + } else if ($this->tokens[$i]['code'] === T_CLASS && isset($this->tokens[$i]['scope_opener']) === true) { + /* + Detect anonymous classes and assign them a different token. + */ + + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + break; + } + } + + if ($this->tokens[$x]['code'] === T_OPEN_PARENTHESIS + || $this->tokens[$x]['code'] === T_OPEN_CURLY_BRACKET + || $this->tokens[$x]['code'] === T_EXTENDS + || $this->tokens[$x]['code'] === T_IMPLEMENTS + ) { + $this->tokens[$i]['code'] = T_ANON_CLASS; + $this->tokens[$i]['type'] = 'T_ANON_CLASS'; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t* token $i on line $line changed from T_CLASS to T_ANON_CLASS".PHP_EOL; + } + + if ($this->tokens[$x]['code'] === T_OPEN_PARENTHESIS + && isset($this->tokens[$x]['parenthesis_closer']) === true + ) { + $closer = $this->tokens[$x]['parenthesis_closer']; + + $this->tokens[$i]['parenthesis_opener'] = $x; + $this->tokens[$i]['parenthesis_closer'] = $closer; + $this->tokens[$i]['parenthesis_owner'] = $i; + $this->tokens[$x]['parenthesis_owner'] = $i; + $this->tokens[$closer]['parenthesis_owner'] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t\t* added parenthesis keys to T_ANON_CLASS token $i on line $line".PHP_EOL; + } + } + + for ($x = ($this->tokens[$i]['scope_opener'] + 1); $x < $this->tokens[$i]['scope_closer']; $x++) { + if (isset($this->tokens[$x]['conditions'][$i]) === false) { + continue; + } + + $this->tokens[$x]['conditions'][$i] = T_ANON_CLASS; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + echo "\t\t* cleaned $x ($type) *".PHP_EOL; + } + } + }//end if + + continue; + } else if ($this->tokens[$i]['code'] === T_FN && isset($this->tokens[($i + 1)]) === true) { + // Possible arrow function. + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false + && $this->tokens[$x]['code'] !== T_BITWISE_AND + ) { + // Non-whitespace content. + break; + } + } + + if (isset($this->tokens[$x]) === true && $this->tokens[$x]['code'] === T_OPEN_PARENTHESIS) { + $ignore = Util\Tokens::$emptyTokens; + $ignore += [ + T_ARRAY => T_ARRAY, + T_CALLABLE => T_CALLABLE, + T_COLON => T_COLON, + T_NAMESPACE => T_NAMESPACE, + T_NS_SEPARATOR => T_NS_SEPARATOR, + T_NULL => T_NULL, + T_NULLABLE => T_NULLABLE, + T_PARENT => T_PARENT, + T_SELF => T_SELF, + T_STATIC => T_STATIC, + T_STRING => T_STRING, + T_TYPE_UNION => T_TYPE_UNION, + T_TYPE_INTERSECTION => T_TYPE_INTERSECTION, + ]; + + $closer = $this->tokens[$x]['parenthesis_closer']; + for ($arrow = ($closer + 1); $arrow < $numTokens; $arrow++) { + if (isset($ignore[$this->tokens[$arrow]['code']]) === false) { + break; + } + } + + if ($this->tokens[$arrow]['code'] === T_DOUBLE_ARROW) { + $endTokens = [ + T_COLON => true, + T_COMMA => true, + T_SEMICOLON => true, + T_CLOSE_PARENTHESIS => true, + T_CLOSE_SQUARE_BRACKET => true, + T_CLOSE_CURLY_BRACKET => true, + T_CLOSE_SHORT_ARRAY => true, + T_OPEN_TAG => true, + T_CLOSE_TAG => true, + ]; + + $inTernary = false; + $lastEndToken = null; + + for ($scopeCloser = ($arrow + 1); $scopeCloser < $numTokens; $scopeCloser++) { + // Arrow function closer should never be shared with the closer of a match + // control structure. + if (isset($this->tokens[$scopeCloser]['scope_closer'], $this->tokens[$scopeCloser]['scope_condition']) === true + && $scopeCloser === $this->tokens[$scopeCloser]['scope_closer'] + && $this->tokens[$this->tokens[$scopeCloser]['scope_condition']]['code'] === T_MATCH + ) { + if ($arrow < $this->tokens[$scopeCloser]['scope_condition']) { + // Match in return value of arrow function. Move on to the next token. + continue; + } + + // Arrow function as return value for the last match case without trailing comma. + if ($lastEndToken !== null) { + $scopeCloser = $lastEndToken; + break; + } + + for ($lastNonEmpty = ($scopeCloser - 1); $lastNonEmpty > $arrow; $lastNonEmpty--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$lastNonEmpty]['code']]) === false) { + $scopeCloser = $lastNonEmpty; + break 2; + } + } + } + + if (isset($endTokens[$this->tokens[$scopeCloser]['code']]) === true) { + if ($lastEndToken !== null + && ((isset($this->tokens[$scopeCloser]['parenthesis_opener']) === true + && $this->tokens[$scopeCloser]['parenthesis_opener'] < $arrow) + || (isset($this->tokens[$scopeCloser]['bracket_opener']) === true + && $this->tokens[$scopeCloser]['bracket_opener'] < $arrow)) + ) { + for ($lastNonEmpty = ($scopeCloser - 1); $lastNonEmpty > $arrow; $lastNonEmpty--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$lastNonEmpty]['code']]) === false) { + $scopeCloser = $lastNonEmpty; + break; + } + } + } + + break; + } + + if ($inTernary === false + && isset($this->tokens[$scopeCloser]['scope_closer'], $this->tokens[$scopeCloser]['scope_condition']) === true + && $scopeCloser === $this->tokens[$scopeCloser]['scope_closer'] + && $this->tokens[$this->tokens[$scopeCloser]['scope_condition']]['code'] === T_FN + ) { + // Found a nested arrow function that already has the closer set and is in + // the same scope as us, so we can use its closer. + break; + } + + if (isset($this->tokens[$scopeCloser]['scope_closer']) === true + && $this->tokens[$scopeCloser]['code'] !== T_INLINE_ELSE + && $this->tokens[$scopeCloser]['code'] !== T_END_HEREDOC + && $this->tokens[$scopeCloser]['code'] !== T_END_NOWDOC + ) { + // We minus 1 here in case the closer can be shared with us. + $scopeCloser = ($this->tokens[$scopeCloser]['scope_closer'] - 1); + continue; + } + + if (isset($this->tokens[$scopeCloser]['parenthesis_closer']) === true) { + $scopeCloser = $this->tokens[$scopeCloser]['parenthesis_closer']; + $lastEndToken = $scopeCloser; + continue; + } + + if (isset($this->tokens[$scopeCloser]['bracket_closer']) === true) { + $scopeCloser = $this->tokens[$scopeCloser]['bracket_closer']; + $lastEndToken = $scopeCloser; + continue; + } + + if ($this->tokens[$scopeCloser]['code'] === T_INLINE_THEN) { + $inTernary = true; + continue; + } + + if ($this->tokens[$scopeCloser]['code'] === T_INLINE_ELSE) { + if ($inTernary === false) { + break; + } + + $inTernary = false; + continue; + } + }//end for + + if ($scopeCloser !== $numTokens) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t=> token $i on line $line processed as arrow function".PHP_EOL; + echo "\t\t* scope opener set to $arrow *".PHP_EOL; + echo "\t\t* scope closer set to $scopeCloser *".PHP_EOL; + echo "\t\t* parenthesis opener set to $x *".PHP_EOL; + echo "\t\t* parenthesis closer set to $closer *".PHP_EOL; + } + + $this->tokens[$i]['code'] = T_FN; + $this->tokens[$i]['type'] = 'T_FN'; + $this->tokens[$i]['scope_condition'] = $i; + $this->tokens[$i]['scope_opener'] = $arrow; + $this->tokens[$i]['scope_closer'] = $scopeCloser; + $this->tokens[$i]['parenthesis_owner'] = $i; + $this->tokens[$i]['parenthesis_opener'] = $x; + $this->tokens[$i]['parenthesis_closer'] = $closer; + + $this->tokens[$arrow]['code'] = T_FN_ARROW; + $this->tokens[$arrow]['type'] = 'T_FN_ARROW'; + + $this->tokens[$arrow]['scope_condition'] = $i; + $this->tokens[$arrow]['scope_opener'] = $arrow; + $this->tokens[$arrow]['scope_closer'] = $scopeCloser; + $this->tokens[$scopeCloser]['scope_condition'] = $i; + $this->tokens[$scopeCloser]['scope_opener'] = $arrow; + $this->tokens[$scopeCloser]['scope_closer'] = $scopeCloser; + + $opener = $this->tokens[$i]['parenthesis_opener']; + $closer = $this->tokens[$i]['parenthesis_closer']; + $this->tokens[$opener]['parenthesis_owner'] = $i; + $this->tokens[$closer]['parenthesis_owner'] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$arrow]['line']; + echo "\t\t* token $arrow on line $line changed from T_DOUBLE_ARROW to T_FN_ARROW".PHP_EOL; + } + }//end if + }//end if + }//end if + + // If after all that, the extra tokens are not set, this is not an arrow function. + if (isset($this->tokens[$i]['scope_closer']) === false) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t=> token $i on line $line is not an arrow function".PHP_EOL; + echo "\t\t* token changed from T_FN to T_STRING".PHP_EOL; + } + + $this->tokens[$i]['code'] = T_STRING; + $this->tokens[$i]['type'] = 'T_STRING'; + } + } else if ($this->tokens[$i]['code'] === T_OPEN_SQUARE_BRACKET) { + if (isset($this->tokens[$i]['bracket_closer']) === false) { + continue; + } + + // Unless there is a variable or a bracket before this token, + // it is the start of an array being defined using the short syntax. + $isShortArray = false; + $allowed = [ + T_CLOSE_SQUARE_BRACKET => T_CLOSE_SQUARE_BRACKET, + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_CLOSE_PARENTHESIS => T_CLOSE_PARENTHESIS, + T_VARIABLE => T_VARIABLE, + T_OBJECT_OPERATOR => T_OBJECT_OPERATOR, + T_NULLSAFE_OBJECT_OPERATOR => T_NULLSAFE_OBJECT_OPERATOR, + T_STRING => T_STRING, + T_CONSTANT_ENCAPSED_STRING => T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING => T_DOUBLE_QUOTED_STRING, + ]; + $allowed += Util\Tokens::$magicConstants; + + for ($x = ($i - 1); $x >= 0; $x--) { + // If we hit a scope opener, the statement has ended + // without finding anything, so it's probably an array + // using PHP 7.1 short list syntax. + if (isset($this->tokens[$x]['scope_opener']) === true) { + $isShortArray = true; + break; + } + + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + // Allow for control structures without braces. + if (($this->tokens[$x]['code'] === T_CLOSE_PARENTHESIS + && isset($this->tokens[$x]['parenthesis_owner']) === true + && isset(Util\Tokens::$scopeOpeners[$this->tokens[$this->tokens[$x]['parenthesis_owner']]['code']]) === true) + || isset($allowed[$this->tokens[$x]['code']]) === false + ) { + $isShortArray = true; + } + + break; + } + }//end for + + if ($isShortArray === true) { + $this->tokens[$i]['code'] = T_OPEN_SHORT_ARRAY; + $this->tokens[$i]['type'] = 'T_OPEN_SHORT_ARRAY'; + + $closer = $this->tokens[$i]['bracket_closer']; + $this->tokens[$closer]['code'] = T_CLOSE_SHORT_ARRAY; + $this->tokens[$closer]['type'] = 'T_CLOSE_SHORT_ARRAY'; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t* token $i on line $line changed from T_OPEN_SQUARE_BRACKET to T_OPEN_SHORT_ARRAY".PHP_EOL; + $line = $this->tokens[$closer]['line']; + echo "\t* token $closer on line $line changed from T_CLOSE_SQUARE_BRACKET to T_CLOSE_SHORT_ARRAY".PHP_EOL; + } + } + + continue; + } else if ($this->tokens[$i]['code'] === T_MATCH) { + if (isset($this->tokens[$i]['scope_opener'], $this->tokens[$i]['scope_closer']) === false) { + // Not a match expression after all. + $this->tokens[$i]['code'] = T_STRING; + $this->tokens[$i]['type'] = 'T_STRING'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $i changed from T_MATCH to T_STRING".PHP_EOL; + } + + if (isset($this->tokens[$i]['parenthesis_opener'], $this->tokens[$i]['parenthesis_closer']) === true) { + $opener = $this->tokens[$i]['parenthesis_opener']; + $closer = $this->tokens[$i]['parenthesis_closer']; + unset( + $this->tokens[$opener]['parenthesis_owner'], + $this->tokens[$closer]['parenthesis_owner'] + ); + unset( + $this->tokens[$i]['parenthesis_opener'], + $this->tokens[$i]['parenthesis_closer'], + $this->tokens[$i]['parenthesis_owner'] + ); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* cleaned parenthesis of token $i *".PHP_EOL; + } + } + } else { + // Retokenize the double arrows for match expression cases to `T_MATCH_ARROW`. + $searchFor = [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_OPEN_SQUARE_BRACKET => T_OPEN_SQUARE_BRACKET, + T_OPEN_PARENTHESIS => T_OPEN_PARENTHESIS, + T_OPEN_SHORT_ARRAY => T_OPEN_SHORT_ARRAY, + T_DOUBLE_ARROW => T_DOUBLE_ARROW, + ]; + $searchFor += Util\Tokens::$scopeOpeners; + + for ($x = ($this->tokens[$i]['scope_opener'] + 1); $x < $this->tokens[$i]['scope_closer']; $x++) { + if (isset($searchFor[$this->tokens[$x]['code']]) === false) { + continue; + } + + if (isset($this->tokens[$x]['scope_closer']) === true) { + $x = $this->tokens[$x]['scope_closer']; + continue; + } + + if (isset($this->tokens[$x]['parenthesis_closer']) === true) { + $x = $this->tokens[$x]['parenthesis_closer']; + continue; + } + + if (isset($this->tokens[$x]['bracket_closer']) === true) { + $x = $this->tokens[$x]['bracket_closer']; + continue; + } + + // This must be a double arrow, but make sure anyhow. + if ($this->tokens[$x]['code'] === T_DOUBLE_ARROW) { + $this->tokens[$x]['code'] = T_MATCH_ARROW; + $this->tokens[$x]['type'] = 'T_MATCH_ARROW'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t* token $x changed from T_DOUBLE_ARROW to T_MATCH_ARROW".PHP_EOL; + } + } + }//end for + }//end if + + continue; + } else if ($this->tokens[$i]['code'] === T_BITWISE_OR + || $this->tokens[$i]['code'] === T_BITWISE_AND + ) { + /* + Convert "|" to T_TYPE_UNION or leave as T_BITWISE_OR. + Convert "&" to T_TYPE_INTERSECTION or leave as T_BITWISE_AND. + */ + + $allowed = [ + T_STRING => T_STRING, + T_CALLABLE => T_CALLABLE, + T_SELF => T_SELF, + T_PARENT => T_PARENT, + T_STATIC => T_STATIC, + T_FALSE => T_FALSE, + T_TRUE => T_TRUE, + T_NULL => T_NULL, + T_NAMESPACE => T_NAMESPACE, + T_NS_SEPARATOR => T_NS_SEPARATOR, + ]; + + $suspectedType = null; + $typeTokenCount = 0; + + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === true) { + continue; + } + + if (isset($allowed[$this->tokens[$x]['code']]) === true) { + ++$typeTokenCount; + continue; + } + + if ($typeTokenCount > 0 + && ($this->tokens[$x]['code'] === T_BITWISE_AND + || $this->tokens[$x]['code'] === T_ELLIPSIS) + ) { + // Skip past reference and variadic indicators for parameter types. + continue; + } + + if ($this->tokens[$x]['code'] === T_VARIABLE) { + // Parameter/Property defaults can not contain variables, so this could be a type. + $suspectedType = 'property or parameter'; + break; + } + + if ($this->tokens[$x]['code'] === T_DOUBLE_ARROW) { + // Possible arrow function. + $suspectedType = 'return'; + break; + } + + if ($this->tokens[$x]['code'] === T_SEMICOLON) { + // Possible abstract method or interface method. + $suspectedType = 'return'; + break; + } + + if ($this->tokens[$x]['code'] === T_OPEN_CURLY_BRACKET + && isset($this->tokens[$x]['scope_condition']) === true + && $this->tokens[$this->tokens[$x]['scope_condition']]['code'] === T_FUNCTION + ) { + $suspectedType = 'return'; + } + + break; + }//end for + + if ($typeTokenCount === 0 || isset($suspectedType) === false) { + // Definitely not a union or intersection type, move on. + continue; + } + + if ($suspectedType === 'property or parameter') { + unset($allowed[\T_STATIC]); + } + + $typeTokenCount = 0; + $typeOperators = [$i]; + $confirmed = false; + + for ($x = ($i - 1); $x >= 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === true) { + continue; + } + + if (isset($allowed[$this->tokens[$x]['code']]) === true) { + ++$typeTokenCount; + continue; + } + + // Union and intersection types can't use the nullable operator, but be tolerant to parse errors. + if ($typeTokenCount > 0 && $this->tokens[$x]['code'] === T_NULLABLE) { + continue; + } + + if ($this->tokens[$x]['code'] === T_BITWISE_OR || $this->tokens[$x]['code'] === T_BITWISE_AND) { + $typeOperators[] = $x; + continue; + } + + if ($suspectedType === 'return' && $this->tokens[$x]['code'] === T_COLON) { + $confirmed = true; + break; + } + + if ($suspectedType === 'property or parameter' + && (isset(Util\Tokens::$scopeModifiers[$this->tokens[$x]['code']]) === true + || $this->tokens[$x]['code'] === T_VAR + || $this->tokens[$x]['code'] === T_STATIC + || $this->tokens[$x]['code'] === T_READONLY) + ) { + // This will also confirm constructor property promotion parameters, but that's fine. + $confirmed = true; + } + + break; + }//end for + + if ($confirmed === false + && $suspectedType === 'property or parameter' + && isset($this->tokens[$i]['nested_parenthesis']) === true + ) { + $parens = $this->tokens[$i]['nested_parenthesis']; + $last = end($parens); + + if (isset($this->tokens[$last]['parenthesis_owner']) === true + && $this->tokens[$this->tokens[$last]['parenthesis_owner']]['code'] === T_FUNCTION + ) { + $confirmed = true; + } else { + // No parenthesis owner set, this may be an arrow function which has not yet + // had additional processing done. + if (isset($this->tokens[$last]['parenthesis_opener']) === true) { + for ($x = ($this->tokens[$last]['parenthesis_opener'] - 1); $x >= 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === true) { + continue; + } + + break; + } + + if ($this->tokens[$x]['code'] === T_FN) { + for (--$x; $x >= 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === true + || $this->tokens[$x]['code'] === T_BITWISE_AND + ) { + continue; + } + + break; + } + + if ($this->tokens[$x]['code'] !== T_FUNCTION) { + $confirmed = true; + } + } + }//end if + }//end if + + unset($parens, $last); + }//end if + + if ($confirmed === false) { + // Not a union or intersection type after all, move on. + continue; + } + + foreach ($typeOperators as $x) { + if ($this->tokens[$x]['code'] === T_BITWISE_OR) { + $this->tokens[$x]['code'] = T_TYPE_UNION; + $this->tokens[$x]['type'] = 'T_TYPE_UNION'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$x]['line']; + echo "\t* token $x on line $line changed from T_BITWISE_OR to T_TYPE_UNION".PHP_EOL; + } + } else { + $this->tokens[$x]['code'] = T_TYPE_INTERSECTION; + $this->tokens[$x]['type'] = 'T_TYPE_INTERSECTION'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$x]['line']; + echo "\t* token $x on line $line changed from T_BITWISE_AND to T_TYPE_INTERSECTION".PHP_EOL; + } + } + } + + continue; + } else if ($this->tokens[$i]['code'] === T_STATIC) { + for ($x = ($i - 1); $x > 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + break; + } + } + + if ($this->tokens[$x]['code'] === T_INSTANCEOF) { + $this->tokens[$i]['code'] = T_STRING; + $this->tokens[$i]['type'] = 'T_STRING'; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + echo "\t* token $i on line $line changed from T_STATIC to T_STRING".PHP_EOL; + } + } + + continue; + } else if ($this->tokens[$i]['code'] === T_TRUE + || $this->tokens[$i]['code'] === T_FALSE + || $this->tokens[$i]['code'] === T_NULL + ) { + for ($x = ($i + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + // Non-whitespace content. + break; + } + } + + if ($x !== $numTokens + && isset($this->tstringContexts[$this->tokens[$x]['code']]) === true + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + $type = $this->tokens[$i]['type']; + echo "\t* token $i on line $line changed from $type to T_STRING".PHP_EOL; + } + + $this->tokens[$i]['code'] = T_STRING; + $this->tokens[$i]['type'] = 'T_STRING'; + } + }//end if + + if (($this->tokens[$i]['code'] !== T_CASE + && $this->tokens[$i]['code'] !== T_DEFAULT) + || isset($this->tokens[$i]['scope_opener']) === false + ) { + // Only interested in CASE and DEFAULT statements from here on in. + continue; + } + + $scopeOpener = $this->tokens[$i]['scope_opener']; + $scopeCloser = $this->tokens[$i]['scope_closer']; + + // If the first char after the opener is a curly brace + // and that brace has been ignored, it is actually + // opening this case statement and the opener and closer are + // probably set incorrectly. + for ($x = ($scopeOpener + 1); $x < $numTokens; $x++) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === false) { + // Non-whitespace content. + break; + } + } + + if ($this->tokens[$x]['code'] === T_CASE || $this->tokens[$x]['code'] === T_DEFAULT) { + // Special case for multiple CASE statements that share the same + // closer. Because we are going backwards through the file, this next + // CASE statement is already fixed, so just use its closer and don't + // worry about fixing anything. + $newCloser = $this->tokens[$x]['scope_closer']; + $this->tokens[$i]['scope_closer'] = $newCloser; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $oldType = $this->tokens[$scopeCloser]['type']; + $newType = $this->tokens[$newCloser]['type']; + $line = $this->tokens[$i]['line']; + echo "\t* token $i (T_CASE) on line $line closer changed from $scopeCloser ($oldType) to $newCloser ($newType)".PHP_EOL; + } + + continue; + } + + if ($this->tokens[$x]['code'] !== T_OPEN_CURLY_BRACKET + || isset($this->tokens[$x]['scope_condition']) === true + ) { + // Not a CASE/DEFAULT with a curly brace opener. + continue; + } + + // The closer for this CASE/DEFAULT should be the closing curly brace and + // not whatever it already is. The opener needs to be the opening curly + // brace so everything matches up. + $newCloser = $this->tokens[$x]['bracket_closer']; + foreach ([$i, $x, $newCloser] as $index) { + $this->tokens[$index]['scope_condition'] = $i; + $this->tokens[$index]['scope_opener'] = $x; + $this->tokens[$index]['scope_closer'] = $newCloser; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$i]['line']; + $tokenType = $this->tokens[$i]['type']; + + $oldType = $this->tokens[$scopeOpener]['type']; + $newType = $this->tokens[$x]['type']; + echo "\t* token $i ($tokenType) on line $line opener changed from $scopeOpener ($oldType) to $x ($newType)".PHP_EOL; + + $oldType = $this->tokens[$scopeCloser]['type']; + $newType = $this->tokens[$newCloser]['type']; + echo "\t* token $i ($tokenType) on line $line closer changed from $scopeCloser ($oldType) to $newCloser ($newType)".PHP_EOL; + } + + if ($this->tokens[$scopeOpener]['scope_condition'] === $i) { + unset($this->tokens[$scopeOpener]['scope_condition']); + unset($this->tokens[$scopeOpener]['scope_opener']); + unset($this->tokens[$scopeOpener]['scope_closer']); + } + + if ($this->tokens[$scopeCloser]['scope_condition'] === $i) { + unset($this->tokens[$scopeCloser]['scope_condition']); + unset($this->tokens[$scopeCloser]['scope_opener']); + unset($this->tokens[$scopeCloser]['scope_closer']); + } else { + // We were using a shared closer. All tokens that were + // sharing this closer with us, except for the scope condition + // and it's opener, need to now point to the new closer. + $condition = $this->tokens[$scopeCloser]['scope_condition']; + $start = ($this->tokens[$condition]['scope_opener'] + 1); + for ($y = $start; $y < $scopeCloser; $y++) { + if (isset($this->tokens[$y]['scope_closer']) === true + && $this->tokens[$y]['scope_closer'] === $scopeCloser + ) { + $this->tokens[$y]['scope_closer'] = $newCloser; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $line = $this->tokens[$y]['line']; + $tokenType = $this->tokens[$y]['type']; + $oldType = $this->tokens[$scopeCloser]['type']; + $newType = $this->tokens[$newCloser]['type']; + echo "\t\t* token $y ($tokenType) on line $line closer changed from $scopeCloser ($oldType) to $newCloser ($newType)".PHP_EOL; + } + } + } + }//end if + + unset($this->tokens[$x]['bracket_opener']); + unset($this->tokens[$x]['bracket_closer']); + unset($this->tokens[$newCloser]['bracket_opener']); + unset($this->tokens[$newCloser]['bracket_closer']); + $this->tokens[$scopeCloser]['conditions'][] = $i; + + // Now fix up all the tokens that think they are + // inside the CASE/DEFAULT statement when they are really outside. + for ($x = $newCloser; $x < $scopeCloser; $x++) { + foreach ($this->tokens[$x]['conditions'] as $num => $oldCond) { + if ($oldCond === $this->tokens[$i]['code']) { + $oldConditions = $this->tokens[$x]['conditions']; + unset($this->tokens[$x]['conditions'][$num]); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + $oldConds = ''; + foreach ($oldConditions as $condition) { + $oldConds .= Util\Tokens::tokenName($condition).','; + } + + $oldConds = rtrim($oldConds, ','); + + $newConds = ''; + foreach ($this->tokens[$x]['conditions'] as $condition) { + $newConds .= Util\Tokens::tokenName($condition).','; + } + + $newConds = rtrim($newConds, ','); + + echo "\t\t* cleaned $x ($type) *".PHP_EOL; + echo "\t\t\t=> conditions changed from $oldConds to $newConds".PHP_EOL; + } + + break; + }//end if + }//end foreach + }//end for + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END ADDITIONAL PHP PROCESSING ***".PHP_EOL; + } + + }//end processAdditional() + + + /** + * Takes a token produced from token_get_all() and produces a + * more uniform token. + * + * @param string|array $token The token to convert. + * + * @return array The new token. + */ + public static function standardiseToken($token) + { + if (isset($token[1]) === false) { + if (isset(self::$resolveTokenCache[$token[0]]) === true) { + return self::$resolveTokenCache[$token[0]]; + } + } else { + $cacheKey = null; + if ($token[0] === T_STRING) { + $cacheKey = strtolower($token[1]); + } else if ($token[0] !== T_CURLY_OPEN) { + $cacheKey = $token[0]; + } + + if ($cacheKey !== null && isset(self::$resolveTokenCache[$cacheKey]) === true) { + $newToken = self::$resolveTokenCache[$cacheKey]; + $newToken['content'] = $token[1]; + return $newToken; + } + } + + if (isset($token[1]) === false) { + return self::resolveSimpleToken($token[0]); + } + + if ($token[0] === T_STRING) { + switch ($cacheKey) { + case 'false': + $newToken['type'] = 'T_FALSE'; + break; + case 'true': + $newToken['type'] = 'T_TRUE'; + break; + case 'null': + $newToken['type'] = 'T_NULL'; + break; + case 'self': + $newToken['type'] = 'T_SELF'; + break; + case 'parent': + $newToken['type'] = 'T_PARENT'; + break; + default: + $newToken['type'] = 'T_STRING'; + break; + } + + $newToken['code'] = constant($newToken['type']); + + self::$resolveTokenCache[$cacheKey] = $newToken; + } else if ($token[0] === T_CURLY_OPEN) { + $newToken = [ + 'code' => T_OPEN_CURLY_BRACKET, + 'type' => 'T_OPEN_CURLY_BRACKET', + ]; + } else { + $newToken = [ + 'code' => $token[0], + 'type' => Util\Tokens::tokenName($token[0]), + ]; + + self::$resolveTokenCache[$token[0]] = $newToken; + }//end if + + $newToken['content'] = $token[1]; + return $newToken; + + }//end standardiseToken() + + + /** + * Converts simple tokens into a format that conforms to complex tokens + * produced by token_get_all(). + * + * Simple tokens are tokens that are not in array form when produced from + * token_get_all(). + * + * @param string $token The simple token to convert. + * + * @return array The new token in array format. + */ + public static function resolveSimpleToken($token) + { + $newToken = []; + + switch ($token) { + case '{': + $newToken['type'] = 'T_OPEN_CURLY_BRACKET'; + break; + case '}': + $newToken['type'] = 'T_CLOSE_CURLY_BRACKET'; + break; + case '[': + $newToken['type'] = 'T_OPEN_SQUARE_BRACKET'; + break; + case ']': + $newToken['type'] = 'T_CLOSE_SQUARE_BRACKET'; + break; + case '(': + $newToken['type'] = 'T_OPEN_PARENTHESIS'; + break; + case ')': + $newToken['type'] = 'T_CLOSE_PARENTHESIS'; + break; + case ':': + $newToken['type'] = 'T_COLON'; + break; + case '.': + $newToken['type'] = 'T_STRING_CONCAT'; + break; + case ';': + $newToken['type'] = 'T_SEMICOLON'; + break; + case '=': + $newToken['type'] = 'T_EQUAL'; + break; + case '*': + $newToken['type'] = 'T_MULTIPLY'; + break; + case '/': + $newToken['type'] = 'T_DIVIDE'; + break; + case '+': + $newToken['type'] = 'T_PLUS'; + break; + case '-': + $newToken['type'] = 'T_MINUS'; + break; + case '%': + $newToken['type'] = 'T_MODULUS'; + break; + case '^': + $newToken['type'] = 'T_BITWISE_XOR'; + break; + case '&': + $newToken['type'] = 'T_BITWISE_AND'; + break; + case '|': + $newToken['type'] = 'T_BITWISE_OR'; + break; + case '~': + $newToken['type'] = 'T_BITWISE_NOT'; + break; + case '<': + $newToken['type'] = 'T_LESS_THAN'; + break; + case '>': + $newToken['type'] = 'T_GREATER_THAN'; + break; + case '!': + $newToken['type'] = 'T_BOOLEAN_NOT'; + break; + case ',': + $newToken['type'] = 'T_COMMA'; + break; + case '@': + $newToken['type'] = 'T_ASPERAND'; + break; + case '$': + $newToken['type'] = 'T_DOLLAR'; + break; + case '`': + $newToken['type'] = 'T_BACKTICK'; + break; + default: + $newToken['type'] = 'T_NONE'; + break; + }//end switch + + $newToken['code'] = constant($newToken['type']); + $newToken['content'] = $token; + + self::$resolveTokenCache[$token] = $newToken; + return $newToken; + + }//end resolveSimpleToken() + + + /** + * Finds a "closer" token (closing parenthesis or square bracket for example) + * Handle parenthesis balancing while searching for closing token + * + * @param array $tokens The list of tokens to iterate searching the closing token (as returned by token_get_all) + * @param int $start The starting position + * @param string|string[] $openerTokens The opening character + * @param string $closerChar The closing character + * + * @return int|null The position of the closing token, if found. NULL otherwise. + */ + private function findCloser(array &$tokens, $start, $openerTokens, $closerChar) + { + $numTokens = count($tokens); + $stack = [0]; + $closer = null; + $openerTokens = (array) $openerTokens; + + for ($x = $start; $x < $numTokens; $x++) { + if (in_array($tokens[$x], $openerTokens, true) === true + || (is_array($tokens[$x]) === true && in_array($tokens[$x][1], $openerTokens, true) === true) + ) { + $stack[] = $x; + } else if ($tokens[$x] === $closerChar) { + array_pop($stack); + if (empty($stack) === true) { + $closer = $x; + break; + } + } + } + + return $closer; + + }//end findCloser() + + + /** + * PHP 8 attributes parser for PHP < 8 + * Handles single-line and multiline attributes. + * + * @param array $tokens The original array of tokens (as returned by token_get_all) + * @param int $stackPtr The current position in token array + * + * @return array|null The array of parsed attribute tokens + */ + private function parsePhpAttribute(array &$tokens, $stackPtr) + { + + $token = $tokens[$stackPtr]; + + $commentBody = substr($token[1], 2); + $subTokens = @token_get_all(' $subToken) { + if (is_array($subToken) === true + && $subToken[0] === T_COMMENT + && strpos($subToken[1], '#[') === 0 + ) { + $reparsed = $this->parsePhpAttribute($subTokens, $i); + if ($reparsed !== null) { + array_splice($subTokens, $i, 1, $reparsed); + } else { + $subToken[0] = T_ATTRIBUTE; + } + } + } + + array_splice($subTokens, 0, 1, [[T_ATTRIBUTE, '#[']]); + + // Go looking for the close bracket. + $bracketCloser = $this->findCloser($subTokens, 1, '[', ']'); + if (PHP_VERSION_ID < 80000 && $bracketCloser === null) { + foreach (array_slice($tokens, ($stackPtr + 1)) as $token) { + if (is_array($token) === true) { + $commentBody .= $token[1]; + } else { + $commentBody .= $token; + } + } + + $subTokens = @token_get_all('findCloser($subTokens, 1, '[', ']'); + if ($bracketCloser !== null) { + array_splice($tokens, ($stackPtr + 1), count($tokens), array_slice($subTokens, ($bracketCloser + 1))); + $subTokens = array_slice($subTokens, 0, ($bracketCloser + 1)); + } + } + + if ($bracketCloser === null) { + return null; + } + + return $subTokens; + + }//end parsePhpAttribute() + + + /** + * Creates a map for the attributes tokens that surround other tokens. + * + * @return void + */ + private function createAttributesNestingMap() + { + $map = []; + for ($i = 0; $i < $this->numTokens; $i++) { + if (isset($this->tokens[$i]['attribute_opener']) === true + && $i === $this->tokens[$i]['attribute_opener'] + ) { + if (empty($map) === false) { + $this->tokens[$i]['nested_attributes'] = $map; + } + + if (isset($this->tokens[$i]['attribute_closer']) === true) { + $map[$this->tokens[$i]['attribute_opener']] + = $this->tokens[$i]['attribute_closer']; + } + } else if (isset($this->tokens[$i]['attribute_closer']) === true + && $i === $this->tokens[$i]['attribute_closer'] + ) { + array_pop($map); + if (empty($map) === false) { + $this->tokens[$i]['nested_attributes'] = $map; + } + } else { + if (empty($map) === false) { + $this->tokens[$i]['nested_attributes'] = $map; + } + }//end if + }//end for + + }//end createAttributesNestingMap() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Tokenizers/Tokenizer.php b/vendor/squizlabs/php_codesniffer/src/Tokenizers/Tokenizer.php new file mode 100644 index 0000000..bfe8c7a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Tokenizers/Tokenizer.php @@ -0,0 +1,1734 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tokenizers; + +use PHP_CodeSniffer\Exceptions\TokenizerException; +use PHP_CodeSniffer\Util; + +abstract class Tokenizer +{ + + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + protected $config = null; + + /** + * The EOL char used in the content. + * + * @var string + */ + protected $eolChar = ''; + + /** + * A token-based representation of the content. + * + * @var array + */ + protected $tokens = []; + + /** + * The number of tokens in the tokens array. + * + * @var integer + */ + protected $numTokens = 0; + + /** + * A list of tokens that are allowed to open a scope. + * + * @var array + */ + public $scopeOpeners = []; + + /** + * A list of tokens that end the scope. + * + * @var array + */ + public $endScopeTokens = []; + + /** + * Known lengths of tokens. + * + * @var array + */ + public $knownLengths = []; + + /** + * A list of lines being ignored due to error suppression comments. + * + * @var array + */ + public $ignoredLines = []; + + + /** + * Initialise and run the tokenizer. + * + * @param string $content The content to tokenize, + * @param \PHP_CodeSniffer\Config | null $config The config data for the run. + * @param string $eolChar The EOL char used in the content. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\TokenizerException If the file appears to be minified. + */ + public function __construct($content, $config, $eolChar='\n') + { + $this->eolChar = $eolChar; + + $this->config = $config; + $this->tokens = $this->tokenize($content); + + if ($config === null) { + return; + } + + $this->createPositionMap(); + $this->createTokenMap(); + $this->createParenthesisNestingMap(); + $this->createScopeMap(); + $this->createLevelMap(); + + // Allow the tokenizer to do additional processing if required. + $this->processAdditional(); + + }//end __construct() + + + /** + * Checks the content to see if it looks minified. + * + * @param string $content The content to tokenize. + * @param string $eolChar The EOL char used in the content. + * + * @return boolean + */ + protected function isMinifiedContent($content, $eolChar='\n') + { + // Minified files often have a very large number of characters per line + // and cause issues when tokenizing. + $numChars = strlen($content); + $numLines = (substr_count($content, $eolChar) + 1); + $average = ($numChars / $numLines); + if ($average > 100) { + return true; + } + + return false; + + }//end isMinifiedContent() + + + /** + * Gets the array of tokens. + * + * @return array + */ + public function getTokens() + { + return $this->tokens; + + }//end getTokens() + + + /** + * Creates an array of tokens when given some content. + * + * @param string $string The string to tokenize. + * + * @return array + */ + abstract protected function tokenize($string); + + + /** + * Performs additional processing after main tokenizing. + * + * @return void + */ + abstract protected function processAdditional(); + + + /** + * Sets token position information. + * + * Can also convert tabs into spaces. Each tab can represent between + * 1 and $width spaces, so this cannot be a straight string replace. + * + * @return void + */ + private function createPositionMap() + { + $currColumn = 1; + $lineNumber = 1; + $eolLen = strlen($this->eolChar); + $ignoring = null; + $inTests = defined('PHP_CODESNIFFER_IN_TESTS'); + + $checkEncoding = false; + if (function_exists('iconv_strlen') === true) { + $checkEncoding = true; + } + + $checkAnnotations = $this->config->annotations; + $encoding = $this->config->encoding; + $tabWidth = $this->config->tabWidth; + + $tokensWithTabs = [ + T_WHITESPACE => true, + T_COMMENT => true, + T_DOC_COMMENT => true, + T_DOC_COMMENT_WHITESPACE => true, + T_DOC_COMMENT_STRING => true, + T_CONSTANT_ENCAPSED_STRING => true, + T_DOUBLE_QUOTED_STRING => true, + T_HEREDOC => true, + T_NOWDOC => true, + T_END_HEREDOC => true, + T_END_NOWDOC => true, + T_INLINE_HTML => true, + ]; + + $this->numTokens = count($this->tokens); + for ($i = 0; $i < $this->numTokens; $i++) { + $this->tokens[$i]['line'] = $lineNumber; + $this->tokens[$i]['column'] = $currColumn; + + if (isset($this->knownLengths[$this->tokens[$i]['code']]) === true) { + // There are no tabs in the tokens we know the length of. + $length = $this->knownLengths[$this->tokens[$i]['code']]; + $currColumn += $length; + } else if ($tabWidth === 0 + || isset($tokensWithTabs[$this->tokens[$i]['code']]) === false + || strpos($this->tokens[$i]['content'], "\t") === false + ) { + // There are no tabs in this content, or we aren't replacing them. + if ($checkEncoding === true) { + // Not using the default encoding, so take a bit more care. + $oldLevel = error_reporting(); + error_reporting(0); + $length = iconv_strlen($this->tokens[$i]['content'], $encoding); + error_reporting($oldLevel); + + if ($length === false) { + // String contained invalid characters, so revert to default. + $length = strlen($this->tokens[$i]['content']); + } + } else { + $length = strlen($this->tokens[$i]['content']); + } + + $currColumn += $length; + } else { + $this->replaceTabsInToken($this->tokens[$i]); + $length = $this->tokens[$i]['length']; + $currColumn += $length; + }//end if + + $this->tokens[$i]['length'] = $length; + + if (isset($this->knownLengths[$this->tokens[$i]['code']]) === false + && strpos($this->tokens[$i]['content'], $this->eolChar) !== false + ) { + $lineNumber++; + $currColumn = 1; + + // Newline chars are not counted in the token length. + $this->tokens[$i]['length'] -= $eolLen; + } + + if ($this->tokens[$i]['code'] === T_COMMENT + || $this->tokens[$i]['code'] === T_DOC_COMMENT_STRING + || $this->tokens[$i]['code'] === T_DOC_COMMENT_TAG + || ($inTests === true && $this->tokens[$i]['code'] === T_INLINE_HTML) + ) { + $commentText = ltrim($this->tokens[$i]['content'], " \t/*#"); + $commentText = rtrim($commentText, " */\t\r\n"); + $commentTextLower = strtolower($commentText); + if (strpos($commentText, '@codingStandards') !== false) { + // If this comment is the only thing on the line, it tells us + // to ignore the following line. If the line contains other content + // then we are just ignoring this one single line. + $ownLine = false; + if ($i > 0) { + for ($prev = ($i - 1); $prev >= 0; $prev--) { + if ($this->tokens[$prev]['code'] === T_WHITESPACE) { + continue; + } + + break; + } + + if ($this->tokens[$prev]['line'] !== $this->tokens[$i]['line']) { + $ownLine = true; + } + } + + if ($ignoring === null + && strpos($commentText, '@codingStandardsIgnoreStart') !== false + ) { + $ignoring = ['.all' => true]; + if ($ownLine === true) { + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + } + } else if ($ignoring !== null + && strpos($commentText, '@codingStandardsIgnoreEnd') !== false + ) { + if ($ownLine === true) { + $this->ignoredLines[$this->tokens[$i]['line']] = ['.all' => true]; + } else { + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + } + + $ignoring = null; + } else if ($ignoring === null + && strpos($commentText, '@codingStandardsIgnoreLine') !== false + ) { + $ignoring = ['.all' => true]; + if ($ownLine === true) { + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + $this->ignoredLines[($this->tokens[$i]['line'] + 1)] = $ignoring; + } else { + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + } + + $ignoring = null; + }//end if + } else if (substr($commentTextLower, 0, 6) === 'phpcs:' + || substr($commentTextLower, 0, 7) === '@phpcs:' + ) { + // If the @phpcs: syntax is being used, strip the @ to make + // comparisons easier. + if ($commentText[0] === '@') { + $commentText = substr($commentText, 1); + $commentTextLower = strtolower($commentText); + } + + // If there is a comment on the end, strip it off. + $commentStart = strpos($commentTextLower, ' --'); + if ($commentStart !== false) { + $commentText = substr($commentText, 0, $commentStart); + $commentTextLower = strtolower($commentText); + } + + // If this comment is the only thing on the line, it tells us + // to ignore the following line. If the line contains other content + // then we are just ignoring this one single line. + $lineHasOtherContent = false; + $lineHasOtherTokens = false; + if ($i > 0) { + for ($prev = ($i - 1); $prev > 0; $prev--) { + if ($this->tokens[$prev]['line'] !== $this->tokens[$i]['line']) { + // Changed lines. + break; + } + + if ($this->tokens[$prev]['code'] === T_WHITESPACE + || $this->tokens[$prev]['code'] === T_DOC_COMMENT_WHITESPACE + || ($this->tokens[$prev]['code'] === T_INLINE_HTML + && trim($this->tokens[$prev]['content']) === '') + ) { + continue; + } + + $lineHasOtherTokens = true; + + if ($this->tokens[$prev]['code'] === T_OPEN_TAG + || $this->tokens[$prev]['code'] === T_DOC_COMMENT_STAR + ) { + continue; + } + + $lineHasOtherContent = true; + break; + }//end for + + $changedLines = false; + for ($next = $i; $next < $this->numTokens; $next++) { + if ($changedLines === true) { + // Changed lines. + break; + } + + if (isset($this->knownLengths[$this->tokens[$next]['code']]) === false + && strpos($this->tokens[$next]['content'], $this->eolChar) !== false + ) { + // Last token on the current line. + $changedLines = true; + } + + if ($next === $i) { + continue; + } + + if ($this->tokens[$next]['code'] === T_WHITESPACE + || $this->tokens[$next]['code'] === T_DOC_COMMENT_WHITESPACE + || ($this->tokens[$next]['code'] === T_INLINE_HTML + && trim($this->tokens[$next]['content']) === '') + ) { + continue; + } + + $lineHasOtherTokens = true; + + if ($this->tokens[$next]['code'] === T_CLOSE_TAG) { + continue; + } + + $lineHasOtherContent = true; + break; + }//end for + }//end if + + if (substr($commentTextLower, 0, 9) === 'phpcs:set') { + // Ignore standards for complete lines that change sniff settings. + if ($lineHasOtherTokens === false) { + $this->ignoredLines[$this->tokens[$i]['line']] = ['.all' => true]; + } + + // Need to maintain case here, to get the correct sniff code. + $parts = explode(' ', substr($commentText, 10)); + if (count($parts) >= 2) { + $sniffParts = explode('.', $parts[0]); + if (count($sniffParts) >= 3) { + $this->tokens[$i]['sniffCode'] = array_shift($parts); + $this->tokens[$i]['sniffProperty'] = array_shift($parts); + $this->tokens[$i]['sniffPropertyValue'] = rtrim(implode(' ', $parts), " */\r\n"); + } + } + + $this->tokens[$i]['code'] = T_PHPCS_SET; + $this->tokens[$i]['type'] = 'T_PHPCS_SET'; + } else if (substr($commentTextLower, 0, 16) === 'phpcs:ignorefile') { + // The whole file will be ignored, but at least set the correct token. + $this->tokens[$i]['code'] = T_PHPCS_IGNORE_FILE; + $this->tokens[$i]['type'] = 'T_PHPCS_IGNORE_FILE'; + } else if (substr($commentTextLower, 0, 13) === 'phpcs:disable') { + if ($lineHasOtherContent === false) { + // Completely ignore the comment line. + $this->ignoredLines[$this->tokens[$i]['line']] = ['.all' => true]; + } + + if ($ignoring === null) { + $ignoring = []; + } + + $disabledSniffs = []; + + $additionalText = substr($commentText, 14); + if (empty($additionalText) === true) { + $ignoring = ['.all' => true]; + } else { + $parts = explode(',', $additionalText); + foreach ($parts as $sniffCode) { + $sniffCode = trim($sniffCode); + $disabledSniffs[$sniffCode] = true; + $ignoring[$sniffCode] = true; + + // This newly disabled sniff might be disabling an existing + // enabled exception that we are tracking. + if (isset($ignoring['.except']) === true) { + foreach (array_keys($ignoring['.except']) as $ignoredSniffCode) { + if ($ignoredSniffCode === $sniffCode + || strpos($ignoredSniffCode, $sniffCode.'.') === 0 + ) { + unset($ignoring['.except'][$ignoredSniffCode]); + } + } + + if (empty($ignoring['.except']) === true) { + unset($ignoring['.except']); + } + } + }//end foreach + }//end if + + $this->tokens[$i]['code'] = T_PHPCS_DISABLE; + $this->tokens[$i]['type'] = 'T_PHPCS_DISABLE'; + $this->tokens[$i]['sniffCodes'] = $disabledSniffs; + } else if (substr($commentTextLower, 0, 12) === 'phpcs:enable') { + if ($ignoring !== null) { + $enabledSniffs = []; + + $additionalText = substr($commentText, 13); + if (empty($additionalText) === true) { + $ignoring = null; + } else { + $parts = explode(',', $additionalText); + foreach ($parts as $sniffCode) { + $sniffCode = trim($sniffCode); + $enabledSniffs[$sniffCode] = true; + + // This new enabled sniff might remove previously disabled + // sniffs if it is actually a standard or category of sniffs. + foreach (array_keys($ignoring) as $ignoredSniffCode) { + if ($ignoredSniffCode === $sniffCode + || strpos($ignoredSniffCode, $sniffCode.'.') === 0 + ) { + unset($ignoring[$ignoredSniffCode]); + } + } + + // This new enabled sniff might be able to clear up + // previously enabled sniffs if it is actually a standard or + // category of sniffs. + if (isset($ignoring['.except']) === true) { + foreach (array_keys($ignoring['.except']) as $ignoredSniffCode) { + if ($ignoredSniffCode === $sniffCode + || strpos($ignoredSniffCode, $sniffCode.'.') === 0 + ) { + unset($ignoring['.except'][$ignoredSniffCode]); + } + } + } + }//end foreach + + if (empty($ignoring) === true) { + $ignoring = null; + } else { + if (isset($ignoring['.except']) === true) { + $ignoring['.except'] += $enabledSniffs; + } else { + $ignoring['.except'] = $enabledSniffs; + } + } + }//end if + + if ($lineHasOtherContent === false) { + // Completely ignore the comment line. + $this->ignoredLines[$this->tokens[$i]['line']] = ['.all' => true]; + } else { + // The comment is on the same line as the code it is ignoring, + // so respect the new ignore rules. + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + } + + $this->tokens[$i]['sniffCodes'] = $enabledSniffs; + }//end if + + $this->tokens[$i]['code'] = T_PHPCS_ENABLE; + $this->tokens[$i]['type'] = 'T_PHPCS_ENABLE'; + } else if (substr($commentTextLower, 0, 12) === 'phpcs:ignore') { + $ignoreRules = []; + + $additionalText = substr($commentText, 13); + if (empty($additionalText) === true) { + $ignoreRules = ['.all' => true]; + } else { + $parts = explode(',', $additionalText); + foreach ($parts as $sniffCode) { + $ignoreRules[trim($sniffCode)] = true; + } + } + + $this->tokens[$i]['code'] = T_PHPCS_IGNORE; + $this->tokens[$i]['type'] = 'T_PHPCS_IGNORE'; + $this->tokens[$i]['sniffCodes'] = $ignoreRules; + + if ($ignoring !== null) { + $ignoreRules += $ignoring; + } + + if ($lineHasOtherContent === false) { + // Completely ignore the comment line, and set the following + // line to include the ignore rules we've set. + $this->ignoredLines[$this->tokens[$i]['line']] = ['.all' => true]; + $this->ignoredLines[($this->tokens[$i]['line'] + 1)] = $ignoreRules; + } else { + // The comment is on the same line as the code it is ignoring, + // so respect the ignore rules it set. + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoreRules; + } + }//end if + }//end if + }//end if + + if ($ignoring !== null && isset($this->ignoredLines[$this->tokens[$i]['line']]) === false) { + $this->ignoredLines[$this->tokens[$i]['line']] = $ignoring; + } + }//end for + + // If annotations are being ignored, we clear out all the ignore rules + // but leave the annotations tokenized as normal. + if ($checkAnnotations === false) { + $this->ignoredLines = []; + } + + }//end createPositionMap() + + + /** + * Replaces tabs in original token content with spaces. + * + * Each tab can represent between 1 and $config->tabWidth spaces, + * so this cannot be a straight string replace. The original content + * is placed into an orig_content index and the new token length is also + * set in the length index. + * + * @param array $token The token to replace tabs inside. + * @param string $prefix The character to use to represent the start of a tab. + * @param string $padding The character to use to represent the end of a tab. + * @param int $tabWidth The number of spaces each tab represents. + * + * @return void + */ + public function replaceTabsInToken(&$token, $prefix=' ', $padding=' ', $tabWidth=null) + { + $checkEncoding = false; + if (function_exists('iconv_strlen') === true) { + $checkEncoding = true; + } + + $currColumn = $token['column']; + if ($tabWidth === null) { + $tabWidth = $this->config->tabWidth; + if ($tabWidth === 0) { + $tabWidth = 1; + } + } + + if (rtrim($token['content'], "\t") === '') { + // String only contains tabs, so we can shortcut the process. + $numTabs = strlen($token['content']); + + $firstTabSize = ($tabWidth - (($currColumn - 1) % $tabWidth)); + $length = ($firstTabSize + ($tabWidth * ($numTabs - 1))); + $newContent = $prefix.str_repeat($padding, ($length - 1)); + } else { + // We need to determine the length of each tab. + $tabs = explode("\t", $token['content']); + + $numTabs = (count($tabs) - 1); + $tabNum = 0; + $newContent = ''; + $length = 0; + + foreach ($tabs as $content) { + if ($content !== '') { + $newContent .= $content; + if ($checkEncoding === true) { + // Not using the default encoding, so take a bit more care. + $oldLevel = error_reporting(); + error_reporting(0); + $contentLength = iconv_strlen($content, $this->config->encoding); + error_reporting($oldLevel); + if ($contentLength === false) { + // String contained invalid characters, so revert to default. + $contentLength = strlen($content); + } + } else { + $contentLength = strlen($content); + } + + $currColumn += $contentLength; + $length += $contentLength; + } + + // The last piece of content does not have a tab after it. + if ($tabNum === $numTabs) { + break; + } + + // Process the tab that comes after the content. + $tabNum++; + + // Move the pointer to the next tab stop. + $pad = ($tabWidth - ($currColumn + $tabWidth - 1) % $tabWidth); + $currColumn += $pad; + $length += $pad; + $newContent .= $prefix.str_repeat($padding, ($pad - 1)); + }//end foreach + }//end if + + $token['orig_content'] = $token['content']; + $token['content'] = $newContent; + $token['length'] = $length; + + }//end replaceTabsInToken() + + + /** + * Creates a map of brackets positions. + * + * @return void + */ + private function createTokenMap() + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START TOKEN MAP ***".PHP_EOL; + } + + $squareOpeners = []; + $curlyOpeners = []; + $this->numTokens = count($this->tokens); + + $openers = []; + $openOwner = null; + + for ($i = 0; $i < $this->numTokens; $i++) { + /* + Parenthesis mapping. + */ + + if (isset(Util\Tokens::$parenthesisOpeners[$this->tokens[$i]['code']]) === true) { + $this->tokens[$i]['parenthesis_opener'] = null; + $this->tokens[$i]['parenthesis_closer'] = null; + $this->tokens[$i]['parenthesis_owner'] = $i; + $openOwner = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", (count($openers) + 1)); + echo "=> Found parenthesis owner at $i".PHP_EOL; + } + } else if ($this->tokens[$i]['code'] === T_OPEN_PARENTHESIS) { + $openers[] = $i; + $this->tokens[$i]['parenthesis_opener'] = $i; + if ($openOwner !== null) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($openers)); + echo "=> Found parenthesis opener at $i for $openOwner".PHP_EOL; + } + + $this->tokens[$openOwner]['parenthesis_opener'] = $i; + $this->tokens[$i]['parenthesis_owner'] = $openOwner; + $openOwner = null; + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($openers)); + echo "=> Found unowned parenthesis opener at $i".PHP_EOL; + } + } else if ($this->tokens[$i]['code'] === T_CLOSE_PARENTHESIS) { + // Did we set an owner for this set of parenthesis? + $numOpeners = count($openers); + if ($numOpeners !== 0) { + $opener = array_pop($openers); + if (isset($this->tokens[$opener]['parenthesis_owner']) === true) { + $owner = $this->tokens[$opener]['parenthesis_owner']; + + $this->tokens[$owner]['parenthesis_closer'] = $i; + $this->tokens[$i]['parenthesis_owner'] = $owner; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", (count($openers) + 1)); + echo "=> Found parenthesis closer at $i for $owner".PHP_EOL; + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", (count($openers) + 1)); + echo "=> Found unowned parenthesis closer at $i for $opener".PHP_EOL; + } + + $this->tokens[$i]['parenthesis_opener'] = $opener; + $this->tokens[$i]['parenthesis_closer'] = $i; + $this->tokens[$opener]['parenthesis_closer'] = $i; + }//end if + } else if ($this->tokens[$i]['code'] === T_ATTRIBUTE) { + $openers[] = $i; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($openers)); + echo "=> Found attribute opener at $i".PHP_EOL; + } + + $this->tokens[$i]['attribute_opener'] = $i; + $this->tokens[$i]['attribute_closer'] = null; + } else if ($this->tokens[$i]['code'] === T_ATTRIBUTE_END) { + $numOpeners = count($openers); + if ($numOpeners !== 0) { + $opener = array_pop($openers); + if (isset($this->tokens[$opener]['attribute_opener']) === true) { + $this->tokens[$opener]['attribute_closer'] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", (count($openers) + 1)); + echo "=> Found attribute closer at $i for $opener".PHP_EOL; + } + + for ($x = ($opener + 1); $x <= $i; ++$x) { + if (isset($this->tokens[$x]['attribute_closer']) === true) { + continue; + } + + $this->tokens[$x]['attribute_opener'] = $opener; + $this->tokens[$x]['attribute_closer'] = $i; + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", (count($openers) + 1)); + echo "=> Found unowned attribute closer at $i for $opener".PHP_EOL; + } + }//end if + }//end if + + /* + Bracket mapping. + */ + + switch ($this->tokens[$i]['code']) { + case T_OPEN_SQUARE_BRACKET: + $squareOpeners[] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($squareOpeners)); + echo str_repeat("\t", count($curlyOpeners)); + echo "=> Found square bracket opener at $i".PHP_EOL; + } + break; + case T_OPEN_CURLY_BRACKET: + if (isset($this->tokens[$i]['scope_closer']) === false) { + $curlyOpeners[] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($squareOpeners)); + echo str_repeat("\t", count($curlyOpeners)); + echo "=> Found curly bracket opener at $i".PHP_EOL; + } + } + break; + case T_CLOSE_SQUARE_BRACKET: + if (empty($squareOpeners) === false) { + $opener = array_pop($squareOpeners); + $this->tokens[$i]['bracket_opener'] = $opener; + $this->tokens[$i]['bracket_closer'] = $i; + $this->tokens[$opener]['bracket_opener'] = $opener; + $this->tokens[$opener]['bracket_closer'] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($squareOpeners)); + echo str_repeat("\t", count($curlyOpeners)); + echo "\t=> Found square bracket closer at $i for $opener".PHP_EOL; + } + } + break; + case T_CLOSE_CURLY_BRACKET: + if (empty($curlyOpeners) === false + && isset($this->tokens[$i]['scope_opener']) === false + ) { + $opener = array_pop($curlyOpeners); + $this->tokens[$i]['bracket_opener'] = $opener; + $this->tokens[$i]['bracket_closer'] = $i; + $this->tokens[$opener]['bracket_opener'] = $opener; + $this->tokens[$opener]['bracket_closer'] = $i; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", count($squareOpeners)); + echo str_repeat("\t", count($curlyOpeners)); + echo "\t=> Found curly bracket closer at $i for $opener".PHP_EOL; + } + } + break; + default: + continue 2; + }//end switch + }//end for + + // Cleanup for any openers that we didn't find closers for. + // This typically means there was a syntax error breaking things. + foreach ($openers as $opener) { + unset($this->tokens[$opener]['parenthesis_opener']); + unset($this->tokens[$opener]['parenthesis_owner']); + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END TOKEN MAP ***".PHP_EOL; + } + + }//end createTokenMap() + + + /** + * Creates a map for the parenthesis tokens that surround other tokens. + * + * @return void + */ + private function createParenthesisNestingMap() + { + $map = []; + for ($i = 0; $i < $this->numTokens; $i++) { + if (isset($this->tokens[$i]['parenthesis_opener']) === true + && $i === $this->tokens[$i]['parenthesis_opener'] + ) { + if (empty($map) === false) { + $this->tokens[$i]['nested_parenthesis'] = $map; + } + + if (isset($this->tokens[$i]['parenthesis_closer']) === true) { + $map[$this->tokens[$i]['parenthesis_opener']] + = $this->tokens[$i]['parenthesis_closer']; + } + } else if (isset($this->tokens[$i]['parenthesis_closer']) === true + && $i === $this->tokens[$i]['parenthesis_closer'] + ) { + array_pop($map); + if (empty($map) === false) { + $this->tokens[$i]['nested_parenthesis'] = $map; + } + } else { + if (empty($map) === false) { + $this->tokens[$i]['nested_parenthesis'] = $map; + } + }//end if + }//end for + + }//end createParenthesisNestingMap() + + + /** + * Creates a scope map of tokens that open scopes. + * + * @return void + * @see recurseScopeMap() + */ + private function createScopeMap() + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START SCOPE MAP ***".PHP_EOL; + } + + for ($i = 0; $i < $this->numTokens; $i++) { + // Check to see if the current token starts a new scope. + if (isset($this->scopeOpeners[$this->tokens[$i]['code']]) === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$i]['type']; + $content = Util\Common::prepareForOutput($this->tokens[$i]['content']); + echo "\tStart scope map at $i:$type => $content".PHP_EOL; + } + + if (isset($this->tokens[$i]['scope_condition']) === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* already processed, skipping *".PHP_EOL; + } + + continue; + } + + $i = $this->recurseScopeMap($i); + }//end if + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END SCOPE MAP ***".PHP_EOL; + } + + }//end createScopeMap() + + + /** + * Recurses though the scope openers to build a scope map. + * + * @param int $stackPtr The position in the stack of the token that + * opened the scope (eg. an IF token or FOR token). + * @param int $depth How many scope levels down we are. + * @param int $ignore How many curly braces we are ignoring. + * + * @return int The position in the stack that closed the scope. + * @throws \PHP_CodeSniffer\Exceptions\TokenizerException If the nesting level gets too deep. + */ + private function recurseScopeMap($stackPtr, $depth=1, &$ignore=0) + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "=> Begin scope map recursion at token $stackPtr with depth $depth".PHP_EOL; + } + + $opener = null; + $currType = $this->tokens[$stackPtr]['code']; + $startLine = $this->tokens[$stackPtr]['line']; + + // We will need this to restore the value if we end up + // returning a token ID that causes our calling function to go back + // over already ignored braces. + $originalIgnore = $ignore; + + // If the start token for this scope opener is the same as + // the scope token, we have already found our opener. + if (isset($this->scopeOpeners[$currType]['start'][$currType]) === true) { + $opener = $stackPtr; + } + + for ($i = ($stackPtr + 1); $i < $this->numTokens; $i++) { + $tokenType = $this->tokens[$i]['code']; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$i]['type']; + $line = $this->tokens[$i]['line']; + $content = Util\Common::prepareForOutput($this->tokens[$i]['content']); + + echo str_repeat("\t", $depth); + echo "Process token $i on line $line ["; + if ($opener !== null) { + echo "opener:$opener;"; + } + + if ($ignore > 0) { + echo "ignore=$ignore;"; + } + + echo "]: $type => $content".PHP_EOL; + }//end if + + // Very special case for IF statements in PHP that can be defined without + // scope tokens. E.g., if (1) 1; 1 ? (1 ? 1 : 1) : 1; + // If an IF statement below this one has an opener but no + // keyword, the opener will be incorrectly assigned to this IF statement. + // The same case also applies to USE statements, which don't have to have + // openers, so a following USE statement can cause an incorrect brace match. + if (($currType === T_IF || $currType === T_ELSE || $currType === T_USE) + && $opener === null + && ($this->tokens[$i]['code'] === T_SEMICOLON + || $this->tokens[$i]['code'] === T_CLOSE_TAG) + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + if ($this->tokens[$i]['code'] === T_SEMICOLON) { + $closerType = 'semicolon'; + } else { + $closerType = 'close tag'; + } + + echo "=> Found $closerType before scope opener for $stackPtr:$type, bailing".PHP_EOL; + } + + return $i; + } + + // Special case for PHP control structures that have no braces. + // If we find a curly brace closer before we find the opener, + // we're not going to find an opener. That closer probably belongs to + // a control structure higher up. + if ($opener === null + && $ignore === 0 + && $tokenType === T_CLOSE_CURLY_BRACKET + && isset($this->scopeOpeners[$currType]['end'][$tokenType]) === true + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found curly brace closer before scope opener for $stackPtr:$type, bailing".PHP_EOL; + } + + return ($i - 1); + } + + if ($opener !== null + && (isset($this->tokens[$i]['scope_opener']) === false + || $this->scopeOpeners[$this->tokens[$stackPtr]['code']]['shared'] === true) + && isset($this->scopeOpeners[$currType]['end'][$tokenType]) === true + ) { + if ($ignore > 0 && $tokenType === T_CLOSE_CURLY_BRACKET) { + // The last opening bracket must have been for a string + // offset or alike, so let's ignore it. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* finished ignoring curly brace *'.PHP_EOL; + } + + $ignore--; + continue; + } else if ($this->tokens[$opener]['code'] === T_OPEN_CURLY_BRACKET + && $tokenType !== T_CLOSE_CURLY_BRACKET + ) { + // The opener is a curly bracket so the closer must be a curly bracket as well. + // We ignore this closer to handle cases such as T_ELSE or T_ELSEIF being considered + // a closer of T_IF when it should not. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Ignoring non-curly scope closer for $stackPtr:$type".PHP_EOL; + } + } else { + $scopeCloser = $i; + $todo = [ + $stackPtr, + $opener, + ]; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + $closerType = $this->tokens[$scopeCloser]['type']; + echo str_repeat("\t", $depth); + echo "=> Found scope closer ($scopeCloser:$closerType) for $stackPtr:$type".PHP_EOL; + } + + $validCloser = true; + if (($this->tokens[$stackPtr]['code'] === T_IF || $this->tokens[$stackPtr]['code'] === T_ELSEIF) + && ($tokenType === T_ELSE || $tokenType === T_ELSEIF) + ) { + // To be a closer, this token must have an opener. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "* closer needs to be tested *".PHP_EOL; + } + + $i = self::recurseScopeMap($i, ($depth + 1), $ignore); + + if (isset($this->tokens[$scopeCloser]['scope_opener']) === false) { + $validCloser = false; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "* closer is not valid (no opener found) *".PHP_EOL; + } + } else if ($this->tokens[$this->tokens[$scopeCloser]['scope_opener']]['code'] !== $this->tokens[$opener]['code']) { + $validCloser = false; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + $type = $this->tokens[$this->tokens[$scopeCloser]['scope_opener']]['type']; + $openerType = $this->tokens[$opener]['type']; + echo "* closer is not valid (mismatched opener type; $type != $openerType) *".PHP_EOL; + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo "* closer was valid *".PHP_EOL; + } + } else { + // The closer was not processed, so we need to + // complete that token as well. + $todo[] = $scopeCloser; + }//end if + + if ($validCloser === true) { + foreach ($todo as $token) { + $this->tokens[$token]['scope_condition'] = $stackPtr; + $this->tokens[$token]['scope_opener'] = $opener; + $this->tokens[$token]['scope_closer'] = $scopeCloser; + } + + if ($this->scopeOpeners[$this->tokens[$stackPtr]['code']]['shared'] === true) { + // As we are going back to where we started originally, restore + // the ignore value back to its original value. + $ignore = $originalIgnore; + return $opener; + } else if ($scopeCloser === $i + && isset($this->scopeOpeners[$tokenType]) === true + ) { + // Unset scope_condition here or else the token will appear to have + // already been processed, and it will be skipped. Normally we want that, + // but in this case, the token is both a closer and an opener, so + // it needs to act like an opener. This is also why we return the + // token before this one; so the closer has a chance to be processed + // a second time, but as an opener. + unset($this->tokens[$scopeCloser]['scope_condition']); + return ($i - 1); + } else { + return $i; + } + } else { + continue; + }//end if + }//end if + }//end if + + // Is this an opening condition ? + if (isset($this->scopeOpeners[$tokenType]) === true) { + if ($opener === null) { + if ($tokenType === T_USE) { + // PHP use keywords are special because they can be + // used as blocks but also inline in function definitions. + // So if we find them nested inside another opener, just skip them. + continue; + } + + if ($tokenType === T_NAMESPACE) { + // PHP namespace keywords are special because they can be + // used as blocks but also inline as operators. + // So if we find them nested inside another opener, just skip them. + continue; + } + + if ($tokenType === T_FUNCTION + && $this->tokens[$stackPtr]['code'] !== T_FUNCTION + ) { + // Probably a closure, so process it manually. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found function before scope opener for $stackPtr:$type, processing manually".PHP_EOL; + } + + if (isset($this->tokens[$i]['scope_closer']) === true) { + // We've already processed this closure. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* already processed, skipping *'.PHP_EOL; + } + + $i = $this->tokens[$i]['scope_closer']; + continue; + } + + $i = self::recurseScopeMap($i, ($depth + 1), $ignore); + continue; + }//end if + + if ($tokenType === T_CLASS) { + // Probably an anonymous class inside another anonymous class, + // so process it manually. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found class before scope opener for $stackPtr:$type, processing manually".PHP_EOL; + } + + if (isset($this->tokens[$i]['scope_closer']) === true) { + // We've already processed this anon class. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* already processed, skipping *'.PHP_EOL; + } + + $i = $this->tokens[$i]['scope_closer']; + continue; + } + + $i = self::recurseScopeMap($i, ($depth + 1), $ignore); + continue; + }//end if + + // Found another opening condition but still haven't + // found our opener, so we are never going to find one. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found new opening condition before scope opener for $stackPtr:$type, "; + } + + if (($this->tokens[$stackPtr]['code'] === T_IF + || $this->tokens[$stackPtr]['code'] === T_ELSEIF + || $this->tokens[$stackPtr]['code'] === T_ELSE) + && ($this->tokens[$i]['code'] === T_ELSE + || $this->tokens[$i]['code'] === T_ELSEIF) + ) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "continuing".PHP_EOL; + } + + return ($i - 1); + } else { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "backtracking".PHP_EOL; + } + + return $stackPtr; + } + }//end if + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* token is an opening condition *'.PHP_EOL; + } + + $isShared = ($this->scopeOpeners[$tokenType]['shared'] === true); + + if (isset($this->tokens[$i]['scope_condition']) === true) { + // We've been here before. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* already processed, skipping *'.PHP_EOL; + } + + if ($isShared === false + && isset($this->tokens[$i]['scope_closer']) === true + ) { + $i = $this->tokens[$i]['scope_closer']; + } + + continue; + } else if ($currType === $tokenType + && $isShared === false + && $opener === null + ) { + // We haven't yet found our opener, but we have found another + // scope opener which is the same type as us, and we don't + // share openers, so we will never find one. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* it was another token\'s opener, bailing *'.PHP_EOL; + } + + return $stackPtr; + } else { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* searching for opener *'.PHP_EOL; + } + + if (isset($this->scopeOpeners[$tokenType]['end'][T_CLOSE_CURLY_BRACKET]) === true) { + $oldIgnore = $ignore; + $ignore = 0; + } + + // PHP has a max nesting level for functions. Stop before we hit that limit + // because too many loops means we've run into trouble anyway. + if ($depth > 50) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* reached maximum nesting level; aborting *'.PHP_EOL; + } + + throw new TokenizerException('Maximum nesting level reached; file could not be processed'); + } + + $oldDepth = $depth; + if ($isShared === true + && isset($this->scopeOpeners[$tokenType]['with'][$currType]) === true + ) { + // Don't allow the depth to increment because this is + // possibly not a true nesting if we are sharing our closer. + // This can happen, for example, when a SWITCH has a large + // number of CASE statements with the same shared BREAK. + $depth--; + } + + $i = self::recurseScopeMap($i, ($depth + 1), $ignore); + $depth = $oldDepth; + + if (isset($this->scopeOpeners[$tokenType]['end'][T_CLOSE_CURLY_BRACKET]) === true) { + $ignore = $oldIgnore; + } + }//end if + }//end if + + if (isset($this->scopeOpeners[$currType]['start'][$tokenType]) === true + && $opener === null + ) { + if ($tokenType === T_OPEN_CURLY_BRACKET) { + if (isset($this->tokens[$stackPtr]['parenthesis_closer']) === true + && $i < $this->tokens[$stackPtr]['parenthesis_closer'] + ) { + // We found a curly brace inside the condition of the + // current scope opener, so it must be a string offset. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* ignoring curly brace inside condition *'.PHP_EOL; + } + + $ignore++; + } else { + // Make sure this is actually an opener and not a + // string offset (e.g., $var{0}). + for ($x = ($i - 1); $x > 0; $x--) { + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$x]['code']]) === true) { + continue; + } else { + // If the first non-whitespace/comment token looks like this + // brace is a string offset, or this brace is mid-way through + // a new statement, it isn't a scope opener. + $disallowed = Util\Tokens::$assignmentTokens; + $disallowed += [ + T_DOLLAR => true, + T_VARIABLE => true, + T_OBJECT_OPERATOR => true, + T_NULLSAFE_OBJECT_OPERATOR => true, + T_COMMA => true, + T_OPEN_PARENTHESIS => true, + ]; + + if (isset($disallowed[$this->tokens[$x]['code']]) === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* ignoring curly brace *'.PHP_EOL; + } + + $ignore++; + } + + break; + }//end if + }//end for + }//end if + }//end if + + if ($ignore === 0 || $tokenType !== T_OPEN_CURLY_BRACKET) { + $openerNested = isset($this->tokens[$i]['nested_parenthesis']); + $ownerNested = isset($this->tokens[$stackPtr]['nested_parenthesis']); + + if (($openerNested === true && $ownerNested === false) + || ($openerNested === false && $ownerNested === true) + || ($openerNested === true + && $this->tokens[$i]['nested_parenthesis'] !== $this->tokens[$stackPtr]['nested_parenthesis']) + ) { + // We found the a token that looks like the opener, but it's nested differently. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$i]['type']; + echo str_repeat("\t", $depth); + echo "* ignoring possible opener $i:$type as nested parenthesis don't match *".PHP_EOL; + } + } else { + // We found the opening scope token for $currType. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found scope opener for $stackPtr:$type".PHP_EOL; + } + + $opener = $i; + } + }//end if + } else if ($tokenType === T_SEMICOLON + && $opener === null + && (isset($this->tokens[$stackPtr]['parenthesis_closer']) === false + || $i > $this->tokens[$stackPtr]['parenthesis_closer']) + ) { + // Found the end of a statement but still haven't + // found our opener, so we are never going to find one. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found end of statement before scope opener for $stackPtr:$type, continuing".PHP_EOL; + } + + return ($i - 1); + } else if ($tokenType === T_OPEN_PARENTHESIS) { + if (isset($this->tokens[$i]['parenthesis_owner']) === true) { + $owner = $this->tokens[$i]['parenthesis_owner']; + if (isset(Util\Tokens::$scopeOpeners[$this->tokens[$owner]['code']]) === true + && isset($this->tokens[$i]['parenthesis_closer']) === true + ) { + // If we get into here, then we opened a parenthesis for + // a scope (eg. an if or else if) so we need to update the + // start of the line so that when we check to see + // if the closing parenthesis is more than n lines away from + // the statement, we check from the closing parenthesis. + $startLine = $this->tokens[$this->tokens[$i]['parenthesis_closer']]['line']; + } + } + } else if ($tokenType === T_OPEN_CURLY_BRACKET && $opener !== null) { + // We opened something that we don't have a scope opener for. + // Examples of this are curly brackets for string offsets etc. + // We want to ignore this so that we don't have an invalid scope + // map. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* ignoring curly brace *'.PHP_EOL; + } + + $ignore++; + } else if ($tokenType === T_CLOSE_CURLY_BRACKET && $ignore > 0) { + // We found the end token for the opener we were ignoring. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* finished ignoring curly brace *'.PHP_EOL; + } + + $ignore--; + } else if ($opener === null + && isset($this->scopeOpeners[$currType]) === true + ) { + // If we still haven't found the opener after 30 lines, + // we're not going to find it, unless we know it requires + // an opener (in which case we better keep looking) or the last + // token was empty (in which case we'll just confirm there is + // more code in this file and not just a big comment). + if ($this->tokens[$i]['line'] >= ($startLine + 30) + && isset(Util\Tokens::$emptyTokens[$this->tokens[($i - 1)]['code']]) === false + ) { + if ($this->scopeOpeners[$currType]['strict'] === true) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + $lines = ($this->tokens[$i]['line'] - $startLine); + echo str_repeat("\t", $depth); + echo "=> Still looking for $stackPtr:$type scope opener after $lines lines".PHP_EOL; + } + } else { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Couldn't find scope opener for $stackPtr:$type, bailing".PHP_EOL; + } + + return $stackPtr; + } + } + } else if ($opener !== null + && $tokenType !== T_BREAK + && isset($this->endScopeTokens[$tokenType]) === true + ) { + if (isset($this->tokens[$i]['scope_condition']) === false) { + if ($ignore > 0) { + // We found the end token for the opener we were ignoring. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", $depth); + echo '* finished ignoring curly brace *'.PHP_EOL; + } + + $ignore--; + } else { + // We found a token that closes the scope but it doesn't + // have a condition, so it belongs to another token and + // our token doesn't have a closer, so pretend this is + // the closer. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", $depth); + echo "=> Found (unexpected) scope closer for $stackPtr:$type".PHP_EOL; + } + + foreach ([$stackPtr, $opener] as $token) { + $this->tokens[$token]['scope_condition'] = $stackPtr; + $this->tokens[$token]['scope_opener'] = $opener; + $this->tokens[$token]['scope_closer'] = $i; + } + + return ($i - 1); + }//end if + }//end if + }//end if + }//end for + + return $stackPtr; + + }//end recurseScopeMap() + + + /** + * Constructs the level map. + * + * The level map adds a 'level' index to each token which indicates the + * depth that a token within a set of scope blocks. It also adds a + * 'conditions' index which is an array of the scope conditions that opened + * each of the scopes - position 0 being the first scope opener. + * + * @return void + */ + private function createLevelMap() + { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** START LEVEL MAP ***".PHP_EOL; + } + + $this->numTokens = count($this->tokens); + $level = 0; + $conditions = []; + $lastOpener = null; + $openers = []; + + for ($i = 0; $i < $this->numTokens; $i++) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$i]['type']; + $line = $this->tokens[$i]['line']; + $len = $this->tokens[$i]['length']; + $col = $this->tokens[$i]['column']; + + $content = Util\Common::prepareForOutput($this->tokens[$i]['content']); + + echo str_repeat("\t", ($level + 1)); + echo "Process token $i on line $line [col:$col;len:$len;lvl:$level;"; + if (empty($conditions) !== true) { + $conditionString = 'conds;'; + foreach ($conditions as $condition) { + $conditionString .= Util\Tokens::tokenName($condition).','; + } + + echo rtrim($conditionString, ',').';'; + } + + echo "]: $type => $content".PHP_EOL; + }//end if + + $this->tokens[$i]['level'] = $level; + $this->tokens[$i]['conditions'] = $conditions; + + if (isset($this->tokens[$i]['scope_condition']) === true) { + // Check to see if this token opened the scope. + if ($this->tokens[$i]['scope_opener'] === $i) { + $stackPtr = $this->tokens[$i]['scope_condition']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", ($level + 1)); + echo "=> Found scope opener for $stackPtr:$type".PHP_EOL; + } + + $stackPtr = $this->tokens[$i]['scope_condition']; + + // If we find a scope opener that has a shared closer, + // then we need to go back over the condition map that we + // just created and fix ourselves as we just added some + // conditions where there was none. This happens for T_CASE + // statements that are using the same break statement. + if ($lastOpener !== null && $this->tokens[$lastOpener]['scope_closer'] === $this->tokens[$i]['scope_closer']) { + // This opener shares its closer with the previous opener, + // but we still need to check if the two openers share their + // closer with each other directly (like CASE and DEFAULT) + // or if they are just sharing because one doesn't have a + // closer (like CASE with no BREAK using a SWITCHes closer). + $thisType = $this->tokens[$this->tokens[$i]['scope_condition']]['code']; + $opener = $this->tokens[$lastOpener]['scope_condition']; + + $isShared = isset($this->scopeOpeners[$thisType]['with'][$this->tokens[$opener]['code']]); + + reset($this->scopeOpeners[$thisType]['end']); + reset($this->scopeOpeners[$this->tokens[$opener]['code']]['end']); + $sameEnd = (current($this->scopeOpeners[$thisType]['end']) === current($this->scopeOpeners[$this->tokens[$opener]['code']]['end'])); + + if ($isShared === true && $sameEnd === true) { + $badToken = $opener; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$badToken]['type']; + echo str_repeat("\t", ($level + 1)); + echo "* shared closer, cleaning up $badToken:$type *".PHP_EOL; + } + + for ($x = $this->tokens[$i]['scope_condition']; $x <= $i; $x++) { + $oldConditions = $this->tokens[$x]['conditions']; + $oldLevel = $this->tokens[$x]['level']; + $this->tokens[$x]['level']--; + unset($this->tokens[$x]['conditions'][$badToken]); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + $oldConds = ''; + foreach ($oldConditions as $condition) { + $oldConds .= Util\Tokens::tokenName($condition).','; + } + + $oldConds = rtrim($oldConds, ','); + + $newConds = ''; + foreach ($this->tokens[$x]['conditions'] as $condition) { + $newConds .= Util\Tokens::tokenName($condition).','; + } + + $newConds = rtrim($newConds, ','); + + $newLevel = $this->tokens[$x]['level']; + echo str_repeat("\t", ($level + 1)); + echo "* cleaned $x:$type *".PHP_EOL; + echo str_repeat("\t", ($level + 2)); + echo "=> level changed from $oldLevel to $newLevel".PHP_EOL; + echo str_repeat("\t", ($level + 2)); + echo "=> conditions changed from $oldConds to $newConds".PHP_EOL; + }//end if + }//end for + + unset($conditions[$badToken]); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$badToken]['type']; + echo str_repeat("\t", ($level + 1)); + echo "* token $badToken:$type removed from conditions array *".PHP_EOL; + } + + unset($openers[$lastOpener]); + + $level--; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", ($level + 2)); + echo '* level decreased *'.PHP_EOL; + } + }//end if + }//end if + + $level++; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", ($level + 1)); + echo '* level increased *'.PHP_EOL; + } + + $conditions[$stackPtr] = $this->tokens[$stackPtr]['code']; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$stackPtr]['type']; + echo str_repeat("\t", ($level + 1)); + echo "* token $stackPtr:$type added to conditions array *".PHP_EOL; + } + + $lastOpener = $this->tokens[$i]['scope_opener']; + if ($lastOpener !== null) { + $openers[$lastOpener] = $lastOpener; + } + } else if ($lastOpener !== null && $this->tokens[$lastOpener]['scope_closer'] === $i) { + foreach (array_reverse($openers) as $opener) { + if ($this->tokens[$opener]['scope_closer'] === $i) { + $oldOpener = array_pop($openers); + if (empty($openers) === false) { + $lastOpener = array_pop($openers); + $openers[$lastOpener] = $lastOpener; + } else { + $lastOpener = null; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$oldOpener]['type']; + echo str_repeat("\t", ($level + 1)); + echo "=> Found scope closer for $oldOpener:$type".PHP_EOL; + } + + $oldCondition = array_pop($conditions); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", ($level + 1)); + echo '* token '.Util\Tokens::tokenName($oldCondition).' removed from conditions array *'.PHP_EOL; + } + + // Make sure this closer actually belongs to us. + // Either the condition also has to think this is the + // closer, or it has to allow sharing with us. + $condition = $this->tokens[$this->tokens[$i]['scope_condition']]['code']; + if ($condition !== $oldCondition) { + if (isset($this->scopeOpeners[$oldCondition]['with'][$condition]) === false) { + $badToken = $this->tokens[$oldOpener]['scope_condition']; + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = Util\Tokens::tokenName($oldCondition); + echo str_repeat("\t", ($level + 1)); + echo "* scope closer was bad, cleaning up $badToken:$type *".PHP_EOL; + } + + for ($x = ($oldOpener + 1); $x <= $i; $x++) { + $oldConditions = $this->tokens[$x]['conditions']; + $oldLevel = $this->tokens[$x]['level']; + $this->tokens[$x]['level']--; + unset($this->tokens[$x]['conditions'][$badToken]); + if (PHP_CODESNIFFER_VERBOSITY > 1) { + $type = $this->tokens[$x]['type']; + $oldConds = ''; + foreach ($oldConditions as $condition) { + $oldConds .= Util\Tokens::tokenName($condition).','; + } + + $oldConds = rtrim($oldConds, ','); + + $newConds = ''; + foreach ($this->tokens[$x]['conditions'] as $condition) { + $newConds .= Util\Tokens::tokenName($condition).','; + } + + $newConds = rtrim($newConds, ','); + + $newLevel = $this->tokens[$x]['level']; + echo str_repeat("\t", ($level + 1)); + echo "* cleaned $x:$type *".PHP_EOL; + echo str_repeat("\t", ($level + 2)); + echo "=> level changed from $oldLevel to $newLevel".PHP_EOL; + echo str_repeat("\t", ($level + 2)); + echo "=> conditions changed from $oldConds to $newConds".PHP_EOL; + }//end if + }//end for + }//end if + }//end if + + $level--; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo str_repeat("\t", ($level + 2)); + echo '* level decreased *'.PHP_EOL; + } + + $this->tokens[$i]['level'] = $level; + $this->tokens[$i]['conditions'] = $conditions; + }//end if + }//end foreach + }//end if + }//end if + }//end for + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END LEVEL MAP ***".PHP_EOL; + } + + }//end createLevelMap() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Util/Cache.php b/vendor/squizlabs/php_codesniffer/src/Util/Cache.php new file mode 100644 index 0000000..932952e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Util/Cache.php @@ -0,0 +1,351 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Util; + +use PHP_CodeSniffer\Autoload; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; + +class Cache +{ + + /** + * The filesystem location of the cache file. + * + * @var string + */ + private static $path = ''; + + /** + * The cached data. + * + * @var array + */ + private static $cache = []; + + + /** + * Loads existing cache data for the run, if any. + * + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public static function load(Ruleset $ruleset, Config $config) + { + // Look at every loaded sniff class so far and use their file contents + // to generate a hash for the code used during the run. + // At this point, the loaded class list contains the core PHPCS code + // and all sniffs that have been loaded as part of the run. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo PHP_EOL."\tGenerating loaded file list for code hash".PHP_EOL; + } + + $codeHashFiles = []; + + $classes = array_keys(Autoload::getLoadedClasses()); + sort($classes); + + $installDir = dirname(__DIR__); + $installDirLen = strlen($installDir); + $standardDir = $installDir.DIRECTORY_SEPARATOR.'Standards'; + $standardDirLen = strlen($standardDir); + foreach ($classes as $file) { + if (substr($file, 0, $standardDirLen) !== $standardDir) { + if (substr($file, 0, $installDirLen) === $installDir) { + // We are only interested in sniffs here. + continue; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> external file: $file".PHP_EOL; + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> internal sniff: $file".PHP_EOL; + } + + $codeHashFiles[] = $file; + } + + // Add the content of the used rulesets to the hash so that sniff setting + // changes in the ruleset invalidate the cache. + $rulesets = $ruleset->paths; + sort($rulesets); + foreach ($rulesets as $file) { + if (substr($file, 0, $standardDirLen) !== $standardDir) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> external ruleset: $file".PHP_EOL; + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> internal ruleset: $file".PHP_EOL; + } + + $codeHashFiles[] = $file; + } + + // Go through the core PHPCS code and add those files to the file + // hash. This ensures that core PHPCS changes will also invalidate the cache. + // Note that we ignore sniffs here, and any files that don't affect + // the outcome of the run. + $di = new \RecursiveDirectoryIterator( + $installDir, + (\FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS) + ); + $filter = new \RecursiveCallbackFilterIterator( + $di, + function ($file, $key, $iterator) { + // Skip non-php files. + $filename = $file->getFilename(); + if ($file->isFile() === true && substr($filename, -4) !== '.php') { + return false; + } + + $filePath = Common::realpath($key); + if ($filePath === false) { + return false; + } + + if ($iterator->hasChildren() === true + && ($filename === 'Standards' + || $filename === 'Exceptions' + || $filename === 'Reports' + || $filename === 'Generators') + ) { + return false; + } + + return true; + } + ); + + $iterator = new \RecursiveIteratorIterator($filter); + foreach ($iterator as $file) { + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> core file: $file".PHP_EOL; + } + + $codeHashFiles[] = $file->getPathname(); + } + + $codeHash = ''; + sort($codeHashFiles); + foreach ($codeHashFiles as $file) { + $codeHash .= md5_file($file); + } + + $codeHash = md5($codeHash); + + // Along with the code hash, use various settings that can affect + // the results of a run to create a new hash. This hash will be used + // in the cache file name. + $rulesetHash = md5(var_export($ruleset->ignorePatterns, true).var_export($ruleset->includePatterns, true)); + $phpExtensionsHash = md5(var_export(get_loaded_extensions(), true)); + $configData = [ + 'phpVersion' => PHP_VERSION_ID, + 'phpExtensions' => $phpExtensionsHash, + 'tabWidth' => $config->tabWidth, + 'encoding' => $config->encoding, + 'recordErrors' => $config->recordErrors, + 'annotations' => $config->annotations, + 'configData' => Config::getAllConfigData(), + 'codeHash' => $codeHash, + 'rulesetHash' => $rulesetHash, + ]; + + $configString = var_export($configData, true); + $cacheHash = substr(sha1($configString), 0, 12); + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\tGenerating cache key data".PHP_EOL; + foreach ($configData as $key => $value) { + if (is_array($value) === true) { + echo "\t\t=> $key:".PHP_EOL; + foreach ($value as $subKey => $subValue) { + echo "\t\t\t=> $subKey: $subValue".PHP_EOL; + } + + continue; + } + + if ($value === true || $value === false) { + $value = (int) $value; + } + + echo "\t\t=> $key: $value".PHP_EOL; + } + + echo "\t\t=> cacheHash: $cacheHash".PHP_EOL; + }//end if + + if ($config->cacheFile !== null) { + $cacheFile = $config->cacheFile; + } else { + // Determine the common paths for all files being checked. + // We can use this to locate an existing cache file, or to + // determine where to create a new one. + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\tChecking possible cache file paths".PHP_EOL; + } + + $paths = []; + foreach ($config->files as $file) { + $file = Common::realpath($file); + while ($file !== DIRECTORY_SEPARATOR) { + if (isset($paths[$file]) === false) { + $paths[$file] = 1; + } else { + $paths[$file]++; + } + + $lastFile = $file; + $file = dirname($file); + if ($file === $lastFile) { + // Just in case something went wrong, + // we don't want to end up in an infinite loop. + break; + } + } + } + + ksort($paths); + $paths = array_reverse($paths); + + $numFiles = count($config->files); + + $cacheFile = null; + $cacheDir = getenv('XDG_CACHE_HOME'); + if ($cacheDir === false || is_dir($cacheDir) === false) { + $cacheDir = sys_get_temp_dir(); + } + + foreach ($paths as $file => $count) { + if ($count !== $numFiles) { + unset($paths[$file]); + continue; + } + + $fileHash = substr(sha1($file), 0, 12); + $testFile = $cacheDir.DIRECTORY_SEPARATOR."phpcs.$fileHash.$cacheHash.cache"; + if ($cacheFile === null) { + // This will be our default location if we can't find + // an existing file. + $cacheFile = $testFile; + } + + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t\t=> $testFile".PHP_EOL; + echo "\t\t\t * based on shared location: $file *".PHP_EOL; + } + + if (file_exists($testFile) === true) { + $cacheFile = $testFile; + break; + } + }//end foreach + + if ($cacheFile === null) { + // Unlikely, but just in case $paths is empty for some reason. + $cacheFile = $cacheDir.DIRECTORY_SEPARATOR."phpcs.$cacheHash.cache"; + } + }//end if + + self::$path = $cacheFile; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t=> Using cache file: ".self::$path.PHP_EOL; + } + + if (file_exists(self::$path) === true) { + self::$cache = json_decode(file_get_contents(self::$path), true); + + // Verify the contents of the cache file. + if (self::$cache['config'] !== $configData) { + self::$cache = []; + if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* cache was invalid and has been cleared *".PHP_EOL; + } + } + } else if (PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* cache file does not exist *".PHP_EOL; + } + + self::$cache['config'] = $configData; + + }//end load() + + + /** + * Saves the current cache to the filesystem. + * + * @return void + */ + public static function save() + { + file_put_contents(self::$path, json_encode(self::$cache)); + + }//end save() + + + /** + * Retrieves a single entry from the cache. + * + * @param string $key The key of the data to get. If NULL, + * everything in the cache is returned. + * + * @return mixed + */ + public static function get($key=null) + { + if ($key === null) { + return self::$cache; + } + + if (isset(self::$cache[$key]) === true) { + return self::$cache[$key]; + } + + return false; + + }//end get() + + + /** + * Retrieves a single entry from the cache. + * + * @param string $key The key of the data to set. If NULL, + * sets the entire cache. + * @param mixed $value The value to set. + * + * @return void + */ + public static function set($key, $value) + { + if ($key === null) { + self::$cache = $value; + } else { + self::$cache[$key] = $value; + } + + }//end set() + + + /** + * Retrieves the number of cache entries. + * + * @return int + */ + public static function getSize() + { + return (count(self::$cache) - 1); + + }//end getSize() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Util/Common.php b/vendor/squizlabs/php_codesniffer/src/Util/Common.php new file mode 100644 index 0000000..afed49e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Util/Common.php @@ -0,0 +1,570 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Util; + +class Common +{ + + /** + * An array of variable types for param/var we will check. + * + * @var string[] + */ + public static $allowedTypes = [ + 'array', + 'boolean', + 'float', + 'integer', + 'mixed', + 'object', + 'string', + 'resource', + 'callable', + ]; + + + /** + * Return TRUE if the path is a PHAR file. + * + * @param string $path The path to use. + * + * @return bool + */ + public static function isPharFile($path) + { + if (strpos($path, 'phar://') === 0) { + return true; + } + + return false; + + }//end isPharFile() + + + /** + * Checks if a file is readable. + * + * Addresses PHP bug related to reading files from network drives on Windows. + * e.g. when using WSL2. + * + * @param string $path The path to the file. + * + * @return boolean + */ + public static function isReadable($path) + { + if (@is_readable($path) === true) { + return true; + } + + if (@file_exists($path) === true && @is_file($path) === true) { + $f = @fopen($path, 'rb'); + if (fclose($f) === true) { + return true; + } + } + + return false; + + }//end isReadable() + + + /** + * CodeSniffer alternative for realpath. + * + * Allows for PHAR support. + * + * @param string $path The path to use. + * + * @return string|false + */ + public static function realpath($path) + { + // Support the path replacement of ~ with the user's home directory. + if (substr($path, 0, 2) === '~/') { + $homeDir = getenv('HOME'); + if ($homeDir !== false) { + $path = $homeDir.substr($path, 1); + } + } + + // Check for process substitution. + if (strpos($path, '/dev/fd') === 0) { + return str_replace('/dev/fd', 'php://fd', $path); + } + + // No extra work needed if this is not a phar file. + if (self::isPharFile($path) === false) { + return realpath($path); + } + + // Before trying to break down the file path, + // check if it exists first because it will mostly not + // change after running the below code. + if (file_exists($path) === true) { + return $path; + } + + $phar = \Phar::running(false); + $extra = str_replace('phar://'.$phar, '', $path); + $path = realpath($phar); + if ($path === false) { + return false; + } + + $path = 'phar://'.$path.$extra; + if (file_exists($path) === true) { + return $path; + } + + return false; + + }//end realpath() + + + /** + * Removes a base path from the front of a file path. + * + * @param string $path The path of the file. + * @param string $basepath The base path to remove. This should not end + * with a directory separator. + * + * @return string + */ + public static function stripBasepath($path, $basepath) + { + if (empty($basepath) === true) { + return $path; + } + + $basepathLen = strlen($basepath); + if (substr($path, 0, $basepathLen) === $basepath) { + $path = substr($path, $basepathLen); + } + + $path = ltrim($path, DIRECTORY_SEPARATOR); + if ($path === '') { + $path = '.'; + } + + return $path; + + }//end stripBasepath() + + + /** + * Detects the EOL character being used in a string. + * + * @param string $contents The contents to check. + * + * @return string + */ + public static function detectLineEndings($contents) + { + if (preg_match("/\r\n?|\n/", $contents, $matches) !== 1) { + // Assume there are no newlines. + $eolChar = "\n"; + } else { + $eolChar = $matches[0]; + } + + return $eolChar; + + }//end detectLineEndings() + + + /** + * Check if STDIN is a TTY. + * + * @return boolean + */ + public static function isStdinATTY() + { + // The check is slow (especially calling `tty`) so we static + // cache the result. + static $isTTY = null; + + if ($isTTY !== null) { + return $isTTY; + } + + if (defined('STDIN') === false) { + return false; + } + + // If PHP has the POSIX extensions we will use them. + if (function_exists('posix_isatty') === true) { + $isTTY = (posix_isatty(STDIN) === true); + return $isTTY; + } + + // Next try is detecting whether we have `tty` installed and use that. + if (defined('PHP_WINDOWS_VERSION_PLATFORM') === true) { + $devnull = 'NUL'; + $which = 'where'; + } else { + $devnull = '/dev/null'; + $which = 'which'; + } + + $tty = trim(shell_exec("$which tty 2> $devnull")); + if (empty($tty) === false) { + exec("tty -s 2> $devnull", $output, $returnValue); + $isTTY = ($returnValue === 0); + return $isTTY; + } + + // Finally we will use fstat. The solution borrowed from + // https://stackoverflow.com/questions/11327367/detect-if-a-php-script-is-being-run-interactively-or-not + // This doesn't work on Mingw/Cygwin/... using Mintty but they + // have `tty` installed. + $type = [ + 'S_IFMT' => 0170000, + 'S_IFIFO' => 0010000, + ]; + + $stat = fstat(STDIN); + $mode = ($stat['mode'] & $type['S_IFMT']); + $isTTY = ($mode !== $type['S_IFIFO']); + + return $isTTY; + + }//end isStdinATTY() + + + /** + * Escape a path to a system command. + * + * @param string $cmd The path to the system command. + * + * @return string + */ + public static function escapeshellcmd($cmd) + { + $cmd = escapeshellcmd($cmd); + + if (stripos(PHP_OS, 'WIN') === 0) { + // Spaces are not escaped by escapeshellcmd on Windows, but need to be + // for the command to be able to execute. + $cmd = preg_replace('`(? 0) { + return false; + } + + if ($strict === true) { + // Check that there are not two capital letters next to each other. + $length = strlen($string); + $lastCharWasCaps = $classFormat; + + for ($i = 1; $i < $length; $i++) { + $ascii = ord($string[$i]); + if ($ascii >= 48 && $ascii <= 57) { + // The character is a number, so it can't be a capital. + $isCaps = false; + } else { + if (strtoupper($string[$i]) === $string[$i]) { + $isCaps = true; + } else { + $isCaps = false; + } + } + + if ($isCaps === true && $lastCharWasCaps === true) { + return false; + } + + $lastCharWasCaps = $isCaps; + } + }//end if + + return true; + + }//end isCamelCaps() + + + /** + * Returns true if the specified string is in the underscore caps format. + * + * @param string $string The string to verify. + * + * @return boolean + */ + public static function isUnderscoreName($string) + { + // If there are space in the name, it can't be valid. + if (strpos($string, ' ') !== false) { + return false; + } + + $validName = true; + $nameBits = explode('_', $string); + + if (preg_match('|^[A-Z]|', $string) === 0) { + // Name does not begin with a capital letter. + $validName = false; + } else { + foreach ($nameBits as $bit) { + if ($bit === '') { + continue; + } + + if ($bit[0] !== strtoupper($bit[0])) { + $validName = false; + break; + } + } + } + + return $validName; + + }//end isUnderscoreName() + + + /** + * Returns a valid variable type for param/var tags. + * + * If type is not one of the standard types, it must be a custom type. + * Returns the correct type name suggestion if type name is invalid. + * + * @param string $varType The variable type to process. + * + * @return string + */ + public static function suggestType($varType) + { + if ($varType === '') { + return ''; + } + + if (in_array($varType, self::$allowedTypes, true) === true) { + return $varType; + } else { + $lowerVarType = strtolower($varType); + switch ($lowerVarType) { + case 'bool': + case 'boolean': + return 'boolean'; + case 'double': + case 'real': + case 'float': + return 'float'; + case 'int': + case 'integer': + return 'integer'; + case 'array()': + case 'array': + return 'array'; + }//end switch + + if (strpos($lowerVarType, 'array(') !== false) { + // Valid array declaration: + // array, array(type), array(type1 => type2). + $matches = []; + $pattern = '/^array\(\s*([^\s^=^>]*)(\s*=>\s*(.*))?\s*\)/i'; + if (preg_match($pattern, $varType, $matches) !== 0) { + $type1 = ''; + if (isset($matches[1]) === true) { + $type1 = $matches[1]; + } + + $type2 = ''; + if (isset($matches[3]) === true) { + $type2 = $matches[3]; + } + + $type1 = self::suggestType($type1); + $type2 = self::suggestType($type2); + if ($type2 !== '') { + $type2 = ' => '.$type2; + } + + return "array($type1$type2)"; + } else { + return 'array'; + }//end if + } else if (in_array($lowerVarType, self::$allowedTypes, true) === true) { + // A valid type, but not lower cased. + return $lowerVarType; + } else { + // Must be a custom type name. + return $varType; + }//end if + }//end if + + }//end suggestType() + + + /** + * Given a sniff class name, returns the code for the sniff. + * + * @param string $sniffClass The fully qualified sniff class name. + * + * @return string + */ + public static function getSniffCode($sniffClass) + { + $parts = explode('\\', $sniffClass); + $sniff = array_pop($parts); + + if (substr($sniff, -5) === 'Sniff') { + // Sniff class name. + $sniff = substr($sniff, 0, -5); + } else { + // Unit test class name. + $sniff = substr($sniff, 0, -8); + } + + $category = array_pop($parts); + $sniffDir = array_pop($parts); + $standard = array_pop($parts); + $code = $standard.'.'.$category.'.'.$sniff; + return $code; + + }//end getSniffCode() + + + /** + * Removes project-specific information from a sniff class name. + * + * @param string $sniffClass The fully qualified sniff class name. + * + * @return string + */ + public static function cleanSniffClass($sniffClass) + { + $newName = strtolower($sniffClass); + + $sniffPos = strrpos($newName, '\sniffs\\'); + if ($sniffPos === false) { + // Nothing we can do as it isn't in a known format. + return $newName; + } + + $end = (strlen($newName) - $sniffPos + 1); + $start = strrpos($newName, '\\', ($end * -1)); + + if ($start === false) { + // Nothing needs to be cleaned. + return $newName; + } + + $newName = substr($newName, ($start + 1)); + return $newName; + + }//end cleanSniffClass() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Util/Standards.php b/vendor/squizlabs/php_codesniffer/src/Util/Standards.php new file mode 100644 index 0000000..ca1060b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Util/Standards.php @@ -0,0 +1,339 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Util; + +use PHP_CodeSniffer\Config; + +class Standards +{ + + + /** + * Get a list of paths where standards are installed. + * + * Unresolvable relative paths will be excluded from the results. + * + * @return array + */ + public static function getInstalledStandardPaths() + { + $ds = DIRECTORY_SEPARATOR; + + $installedPaths = [dirname(dirname(__DIR__)).$ds.'src'.$ds.'Standards']; + $configPaths = Config::getConfigData('installed_paths'); + if ($configPaths !== null) { + $installedPaths = array_merge($installedPaths, explode(',', $configPaths)); + } + + $resolvedInstalledPaths = []; + foreach ($installedPaths as $installedPath) { + if (substr($installedPath, 0, 1) === '.') { + $installedPath = Common::realPath(__DIR__.$ds.'..'.$ds.'..'.$ds.$installedPath); + if ($installedPath === false) { + continue; + } + } + + $resolvedInstalledPaths[] = $installedPath; + } + + return $resolvedInstalledPaths; + + }//end getInstalledStandardPaths() + + + /** + * Get the details of all coding standards installed. + * + * Coding standards are directories located in the + * CodeSniffer/Standards directory. Valid coding standards + * include a Sniffs subdirectory. + * + * The details returned for each standard are: + * - path: the path to the coding standard's main directory + * - name: the name of the coding standard, as sourced from the ruleset.xml file + * - namespace: the namespace used by the coding standard, as sourced from the ruleset.xml file + * + * If you only need the paths to the installed standards, + * use getInstalledStandardPaths() instead as it performs less work to + * retrieve coding standard names. + * + * @param boolean $includeGeneric If true, the special "Generic" + * coding standard will be included + * if installed. + * @param string $standardsDir A specific directory to look for standards + * in. If not specified, PHP_CodeSniffer will + * look in its default locations. + * + * @return array + * @see getInstalledStandardPaths() + */ + public static function getInstalledStandardDetails( + $includeGeneric=false, + $standardsDir='' + ) { + $rulesets = []; + + if ($standardsDir === '') { + $installedPaths = self::getInstalledStandardPaths(); + } else { + $installedPaths = [$standardsDir]; + } + + foreach ($installedPaths as $standardsDir) { + // Check if the installed dir is actually a standard itself. + $csFile = $standardsDir.'/ruleset.xml'; + if (is_file($csFile) === true) { + $rulesets[] = $csFile; + continue; + } + + if (is_dir($standardsDir) === false) { + continue; + } + + $di = new \DirectoryIterator($standardsDir); + foreach ($di as $file) { + if ($file->isDir() === true && $file->isDot() === false) { + $filename = $file->getFilename(); + + // Ignore the special "Generic" standard. + if ($includeGeneric === false && $filename === 'Generic') { + continue; + } + + // Valid coding standard dirs include a ruleset. + $csFile = $file->getPathname().'/ruleset.xml'; + if (is_file($csFile) === true) { + $rulesets[] = $csFile; + } + } + } + }//end foreach + + $installedStandards = []; + + foreach ($rulesets as $rulesetPath) { + $ruleset = @simplexml_load_string(file_get_contents($rulesetPath)); + if ($ruleset === false) { + continue; + } + + $standardName = (string) $ruleset['name']; + $dirname = basename(dirname($rulesetPath)); + + if (isset($ruleset['namespace']) === true) { + $namespace = (string) $ruleset['namespace']; + } else { + $namespace = $dirname; + } + + $installedStandards[$dirname] = [ + 'path' => dirname($rulesetPath), + 'name' => $standardName, + 'namespace' => $namespace, + ]; + }//end foreach + + return $installedStandards; + + }//end getInstalledStandardDetails() + + + /** + * Get a list of all coding standards installed. + * + * Coding standards are directories located in the + * CodeSniffer/Standards directory. Valid coding standards + * include a Sniffs subdirectory. + * + * @param boolean $includeGeneric If true, the special "Generic" + * coding standard will be included + * if installed. + * @param string $standardsDir A specific directory to look for standards + * in. If not specified, PHP_CodeSniffer will + * look in its default locations. + * + * @return array + * @see isInstalledStandard() + */ + public static function getInstalledStandards( + $includeGeneric=false, + $standardsDir='' + ) { + $installedStandards = []; + + if ($standardsDir === '') { + $installedPaths = self::getInstalledStandardPaths(); + } else { + $installedPaths = [$standardsDir]; + } + + foreach ($installedPaths as $standardsDir) { + // Check if the installed dir is actually a standard itself. + $csFile = $standardsDir.'/ruleset.xml'; + if (is_file($csFile) === true) { + $basename = basename($standardsDir); + $installedStandards[$basename] = $basename; + continue; + } + + if (is_dir($standardsDir) === false) { + // Doesn't exist. + continue; + } + + $di = new \DirectoryIterator($standardsDir); + $standardsInDir = []; + foreach ($di as $file) { + if ($file->isDir() === true && $file->isDot() === false) { + $filename = $file->getFilename(); + + // Ignore the special "Generic" standard. + if ($includeGeneric === false && $filename === 'Generic') { + continue; + } + + // Valid coding standard dirs include a ruleset. + $csFile = $file->getPathname().'/ruleset.xml'; + if (is_file($csFile) === true) { + $standardsInDir[$filename] = $filename; + } + } + } + + natsort($standardsInDir); + $installedStandards += $standardsInDir; + }//end foreach + + return $installedStandards; + + }//end getInstalledStandards() + + + /** + * Determine if a standard is installed. + * + * Coding standards are directories located in the + * CodeSniffer/Standards directory. Valid coding standards + * include a ruleset.xml file. + * + * @param string $standard The name of the coding standard. + * + * @return boolean + * @see getInstalledStandards() + */ + public static function isInstalledStandard($standard) + { + $path = self::getInstalledStandardPath($standard); + if ($path !== null && strpos($path, 'ruleset.xml') !== false) { + return true; + } else { + // This could be a custom standard, installed outside our + // standards directory. + $standard = Common::realPath($standard); + if ($standard === false) { + return false; + } + + // Might be an actual ruleset file itUtil. + // If it has an XML extension, let's at least try it. + if (is_file($standard) === true + && (substr(strtolower($standard), -4) === '.xml' + || substr(strtolower($standard), -9) === '.xml.dist') + ) { + return true; + } + + // If it is a directory with a ruleset.xml file in it, + // it is a standard. + $ruleset = rtrim($standard, ' /\\').DIRECTORY_SEPARATOR.'ruleset.xml'; + if (is_file($ruleset) === true) { + return true; + } + }//end if + + return false; + + }//end isInstalledStandard() + + + /** + * Return the path of an installed coding standard. + * + * Coding standards are directories located in the + * CodeSniffer/Standards directory. Valid coding standards + * include a ruleset.xml file. + * + * @param string $standard The name of the coding standard. + * + * @return string|null + */ + public static function getInstalledStandardPath($standard) + { + if (strpos($standard, '.') !== false) { + return null; + } + + $installedPaths = self::getInstalledStandardPaths(); + foreach ($installedPaths as $installedPath) { + $standardPath = $installedPath.DIRECTORY_SEPARATOR.$standard; + if (file_exists($standardPath) === false) { + if (basename($installedPath) !== $standard) { + continue; + } + + $standardPath = $installedPath; + } + + $path = Common::realpath($standardPath.DIRECTORY_SEPARATOR.'ruleset.xml'); + + if ($path !== false && is_file($path) === true) { + return $path; + } else if (Common::isPharFile($standardPath) === true) { + $path = Common::realpath($standardPath); + if ($path !== false) { + return $path; + } + } + }//end foreach + + return null; + + }//end getInstalledStandardPath() + + + /** + * Prints out a list of installed coding standards. + * + * @return void + */ + public static function printInstalledStandards() + { + $installedStandards = self::getInstalledStandards(); + $numStandards = count($installedStandards); + + if ($numStandards === 0) { + echo 'No coding standards are installed.'.PHP_EOL; + } else { + $lastStandard = array_pop($installedStandards); + if ($numStandards === 1) { + echo "The only coding standard installed is $lastStandard".PHP_EOL; + } else { + $standardList = implode(', ', $installedStandards); + $standardList .= ' and '.$lastStandard; + echo 'The installed coding standards are '.$standardList.PHP_EOL; + } + } + + }//end printInstalledStandards() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Util/Timing.php b/vendor/squizlabs/php_codesniffer/src/Util/Timing.php new file mode 100644 index 0000000..57470c7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Util/Timing.php @@ -0,0 +1,119 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Util; + +class Timing +{ + + /** + * The start time of the run. + * + * @var float + */ + private static $startTime; + + /** + * Used to make sure we only print the run time once per run. + * + * @var boolean + */ + private static $printed = false; + + + /** + * Start recording time for the run. + * + * @return void + */ + public static function startTiming() + { + + self::$startTime = microtime(true); + + }//end startTiming() + + + /** + * Get the duration of the run up to "now". + * + * @return float Duration in microseconds. + */ + public static function getDuration() + { + if (self::$startTime === null) { + // Timing was never started. + return 0; + } + + return ((microtime(true) - self::$startTime) * 1000); + + }//end getDuration() + + + /** + * Convert a duration in microseconds to a human readable duration string. + * + * @param float $duration Duration in microseconds. + * + * @return string + */ + public static function getHumanReadableDuration($duration) + { + $timeString = ''; + if ($duration > 60000) { + $mins = floor($duration / 60000); + $secs = round((fmod($duration, 60000) / 1000), 2); + $timeString = $mins.' mins'; + if ($secs !== 0) { + $timeString .= ", $secs secs"; + } + } else if ($duration > 1000) { + $timeString = round(($duration / 1000), 2).' secs'; + } else { + $timeString = round($duration).'ms'; + } + + return $timeString; + + }//end getHumanReadableDuration() + + + /** + * Print information about the run. + * + * @param boolean $force If TRUE, prints the output even if it has + * already been printed during the run. + * + * @return void + */ + public static function printRunTime($force=false) + { + if ($force === false && self::$printed === true) { + // A double call. + return; + } + + if (self::$startTime === null) { + // Timing was never started. + return; + } + + $duration = self::getDuration(); + $duration = self::getHumanReadableDuration($duration); + + $mem = round((memory_get_peak_usage(true) / (1024 * 1024)), 2).'MB'; + echo "Time: $duration; Memory: $mem".PHP_EOL.PHP_EOL; + + self::$printed = true; + + }//end printRunTime() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Util/Tokens.php b/vendor/squizlabs/php_codesniffer/src/Util/Tokens.php new file mode 100644 index 0000000..ab70e78 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Util/Tokens.php @@ -0,0 +1,810 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Util; + +define('T_NONE', 'PHPCS_T_NONE'); +define('T_OPEN_CURLY_BRACKET', 'PHPCS_T_OPEN_CURLY_BRACKET'); +define('T_CLOSE_CURLY_BRACKET', 'PHPCS_T_CLOSE_CURLY_BRACKET'); +define('T_OPEN_SQUARE_BRACKET', 'PHPCS_T_OPEN_SQUARE_BRACKET'); +define('T_CLOSE_SQUARE_BRACKET', 'PHPCS_T_CLOSE_SQUARE_BRACKET'); +define('T_OPEN_PARENTHESIS', 'PHPCS_T_OPEN_PARENTHESIS'); +define('T_CLOSE_PARENTHESIS', 'PHPCS_T_CLOSE_PARENTHESIS'); +define('T_COLON', 'PHPCS_T_COLON'); +define('T_NULLABLE', 'PHPCS_T_NULLABLE'); +define('T_STRING_CONCAT', 'PHPCS_T_STRING_CONCAT'); +define('T_INLINE_THEN', 'PHPCS_T_INLINE_THEN'); +define('T_INLINE_ELSE', 'PHPCS_T_INLINE_ELSE'); +define('T_NULL', 'PHPCS_T_NULL'); +define('T_FALSE', 'PHPCS_T_FALSE'); +define('T_TRUE', 'PHPCS_T_TRUE'); +define('T_SEMICOLON', 'PHPCS_T_SEMICOLON'); +define('T_EQUAL', 'PHPCS_T_EQUAL'); +define('T_MULTIPLY', 'PHPCS_T_MULTIPLY'); +define('T_DIVIDE', 'PHPCS_T_DIVIDE'); +define('T_PLUS', 'PHPCS_T_PLUS'); +define('T_MINUS', 'PHPCS_T_MINUS'); +define('T_MODULUS', 'PHPCS_T_MODULUS'); +define('T_BITWISE_AND', 'PHPCS_T_BITWISE_AND'); +define('T_BITWISE_OR', 'PHPCS_T_BITWISE_OR'); +define('T_BITWISE_XOR', 'PHPCS_T_BITWISE_XOR'); +define('T_BITWISE_NOT', 'PHPCS_T_BITWISE_NOT'); +define('T_ARRAY_HINT', 'PHPCS_T_ARRAY_HINT'); +define('T_GREATER_THAN', 'PHPCS_T_GREATER_THAN'); +define('T_LESS_THAN', 'PHPCS_T_LESS_THAN'); +define('T_BOOLEAN_NOT', 'PHPCS_T_BOOLEAN_NOT'); +define('T_SELF', 'PHPCS_T_SELF'); +define('T_PARENT', 'PHPCS_T_PARENT'); +define('T_DOUBLE_QUOTED_STRING', 'PHPCS_T_DOUBLE_QUOTED_STRING'); +define('T_COMMA', 'PHPCS_T_COMMA'); +define('T_HEREDOC', 'PHPCS_T_HEREDOC'); +define('T_PROTOTYPE', 'PHPCS_T_PROTOTYPE'); +define('T_THIS', 'PHPCS_T_THIS'); +define('T_REGULAR_EXPRESSION', 'PHPCS_T_REGULAR_EXPRESSION'); +define('T_PROPERTY', 'PHPCS_T_PROPERTY'); +define('T_LABEL', 'PHPCS_T_LABEL'); +define('T_OBJECT', 'PHPCS_T_OBJECT'); +define('T_CLOSE_OBJECT', 'PHPCS_T_CLOSE_OBJECT'); +define('T_COLOUR', 'PHPCS_T_COLOUR'); +define('T_HASH', 'PHPCS_T_HASH'); +define('T_URL', 'PHPCS_T_URL'); +define('T_STYLE', 'PHPCS_T_STYLE'); +define('T_ASPERAND', 'PHPCS_T_ASPERAND'); +define('T_DOLLAR', 'PHPCS_T_DOLLAR'); +define('T_TYPEOF', 'PHPCS_T_TYPEOF'); +define('T_CLOSURE', 'PHPCS_T_CLOSURE'); +define('T_ANON_CLASS', 'PHPCS_T_ANON_CLASS'); +define('T_BACKTICK', 'PHPCS_T_BACKTICK'); +define('T_START_NOWDOC', 'PHPCS_T_START_NOWDOC'); +define('T_NOWDOC', 'PHPCS_T_NOWDOC'); +define('T_END_NOWDOC', 'PHPCS_T_END_NOWDOC'); +define('T_OPEN_SHORT_ARRAY', 'PHPCS_T_OPEN_SHORT_ARRAY'); +define('T_CLOSE_SHORT_ARRAY', 'PHPCS_T_CLOSE_SHORT_ARRAY'); +define('T_GOTO_LABEL', 'PHPCS_T_GOTO_LABEL'); +define('T_BINARY_CAST', 'PHPCS_T_BINARY_CAST'); +define('T_EMBEDDED_PHP', 'PHPCS_T_EMBEDDED_PHP'); +define('T_RETURN_TYPE', 'PHPCS_T_RETURN_TYPE'); +define('T_OPEN_USE_GROUP', 'PHPCS_T_OPEN_USE_GROUP'); +define('T_CLOSE_USE_GROUP', 'PHPCS_T_CLOSE_USE_GROUP'); +define('T_ZSR', 'PHPCS_T_ZSR'); +define('T_ZSR_EQUAL', 'PHPCS_T_ZSR_EQUAL'); +define('T_FN_ARROW', 'PHPCS_T_FN_ARROW'); +define('T_TYPE_UNION', 'PHPCS_T_TYPE_UNION'); +define('T_PARAM_NAME', 'PHPCS_T_PARAM_NAME'); +define('T_MATCH_ARROW', 'PHPCS_T_MATCH_ARROW'); +define('T_MATCH_DEFAULT', 'PHPCS_T_MATCH_DEFAULT'); +define('T_ATTRIBUTE_END', 'PHPCS_T_ATTRIBUTE_END'); +define('T_ENUM_CASE', 'PHPCS_T_ENUM_CASE'); +define('T_TYPE_INTERSECTION', 'PHPCS_T_TYPE_INTERSECTION'); + +// Some PHP 5.5 tokens, replicated for lower versions. +if (defined('T_FINALLY') === false) { + define('T_FINALLY', 'PHPCS_T_FINALLY'); +} + +if (defined('T_YIELD') === false) { + define('T_YIELD', 'PHPCS_T_YIELD'); +} + +// Some PHP 5.6 tokens, replicated for lower versions. +if (defined('T_ELLIPSIS') === false) { + define('T_ELLIPSIS', 'PHPCS_T_ELLIPSIS'); +} + +if (defined('T_POW') === false) { + define('T_POW', 'PHPCS_T_POW'); +} + +if (defined('T_POW_EQUAL') === false) { + define('T_POW_EQUAL', 'PHPCS_T_POW_EQUAL'); +} + +// Some PHP 7 tokens, replicated for lower versions. +if (defined('T_SPACESHIP') === false) { + define('T_SPACESHIP', 'PHPCS_T_SPACESHIP'); +} + +if (defined('T_COALESCE') === false) { + define('T_COALESCE', 'PHPCS_T_COALESCE'); +} + +if (defined('T_COALESCE_EQUAL') === false) { + define('T_COALESCE_EQUAL', 'PHPCS_T_COALESCE_EQUAL'); +} + +if (defined('T_YIELD_FROM') === false) { + define('T_YIELD_FROM', 'PHPCS_T_YIELD_FROM'); +} + +// Some PHP 7.4 tokens, replicated for lower versions. +if (defined('T_BAD_CHARACTER') === false) { + define('T_BAD_CHARACTER', 'PHPCS_T_BAD_CHARACTER'); +} + +if (defined('T_FN') === false) { + define('T_FN', 'PHPCS_T_FN'); +} + +// Some PHP 8.0 tokens, replicated for lower versions. +if (defined('T_NULLSAFE_OBJECT_OPERATOR') === false) { + define('T_NULLSAFE_OBJECT_OPERATOR', 'PHPCS_T_NULLSAFE_OBJECT_OPERATOR'); +} + +if (defined('T_NAME_QUALIFIED') === false) { + define('T_NAME_QUALIFIED', 'PHPCS_T_NAME_QUALIFIED'); +} + +if (defined('T_NAME_FULLY_QUALIFIED') === false) { + define('T_NAME_FULLY_QUALIFIED', 'PHPCS_T_NAME_FULLY_QUALIFIED'); +} + +if (defined('T_NAME_RELATIVE') === false) { + define('T_NAME_RELATIVE', 'PHPCS_T_NAME_RELATIVE'); +} + +if (defined('T_MATCH') === false) { + define('T_MATCH', 'PHPCS_T_MATCH'); +} + +if (defined('T_ATTRIBUTE') === false) { + define('T_ATTRIBUTE', 'PHPCS_T_ATTRIBUTE'); +} + +// Some PHP 8.1 tokens, replicated for lower versions. +if (defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG') === false) { + define('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'PHPCS_T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG'); +} + +if (defined('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG') === false) { + define('T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'PHPCS_T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG'); +} + +if (defined('T_READONLY') === false) { + define('T_READONLY', 'PHPCS_T_READONLY'); +} + +if (defined('T_ENUM') === false) { + define('T_ENUM', 'PHPCS_T_ENUM'); +} + +// Tokens used for parsing doc blocks. +define('T_DOC_COMMENT_STAR', 'PHPCS_T_DOC_COMMENT_STAR'); +define('T_DOC_COMMENT_WHITESPACE', 'PHPCS_T_DOC_COMMENT_WHITESPACE'); +define('T_DOC_COMMENT_TAG', 'PHPCS_T_DOC_COMMENT_TAG'); +define('T_DOC_COMMENT_OPEN_TAG', 'PHPCS_T_DOC_COMMENT_OPEN_TAG'); +define('T_DOC_COMMENT_CLOSE_TAG', 'PHPCS_T_DOC_COMMENT_CLOSE_TAG'); +define('T_DOC_COMMENT_STRING', 'PHPCS_T_DOC_COMMENT_STRING'); + +// Tokens used for PHPCS instruction comments. +define('T_PHPCS_ENABLE', 'PHPCS_T_PHPCS_ENABLE'); +define('T_PHPCS_DISABLE', 'PHPCS_T_PHPCS_DISABLE'); +define('T_PHPCS_SET', 'PHPCS_T_PHPCS_SET'); +define('T_PHPCS_IGNORE', 'PHPCS_T_PHPCS_IGNORE'); +define('T_PHPCS_IGNORE_FILE', 'PHPCS_T_PHPCS_IGNORE_FILE'); + +final class Tokens +{ + + /** + * The token weightings. + * + * @var array + */ + public static $weightings = [ + T_CLASS => 1000, + T_INTERFACE => 1000, + T_TRAIT => 1000, + T_ENUM => 1000, + T_NAMESPACE => 1000, + T_FUNCTION => 100, + T_CLOSURE => 100, + + /* + * Conditions. + */ + + T_WHILE => 50, + T_FOR => 50, + T_FOREACH => 50, + T_IF => 50, + T_ELSE => 50, + T_ELSEIF => 50, + T_DO => 50, + T_TRY => 50, + T_CATCH => 50, + T_FINALLY => 50, + T_SWITCH => 50, + T_MATCH => 50, + + T_SELF => 25, + T_PARENT => 25, + + /* + * Operators and arithmetic. + */ + + T_BITWISE_AND => 8, + T_BITWISE_OR => 8, + T_BITWISE_XOR => 8, + + T_MULTIPLY => 5, + T_DIVIDE => 5, + T_PLUS => 5, + T_MINUS => 5, + T_MODULUS => 5, + T_POW => 5, + T_SPACESHIP => 5, + T_COALESCE => 5, + T_COALESCE_EQUAL => 5, + + T_SL => 5, + T_SR => 5, + T_SL_EQUAL => 5, + T_SR_EQUAL => 5, + + T_EQUAL => 5, + T_AND_EQUAL => 5, + T_CONCAT_EQUAL => 5, + T_DIV_EQUAL => 5, + T_MINUS_EQUAL => 5, + T_MOD_EQUAL => 5, + T_MUL_EQUAL => 5, + T_OR_EQUAL => 5, + T_PLUS_EQUAL => 5, + T_XOR_EQUAL => 5, + + T_BOOLEAN_AND => 5, + T_BOOLEAN_OR => 5, + + /* + * Equality. + */ + + T_IS_EQUAL => 5, + T_IS_NOT_EQUAL => 5, + T_IS_IDENTICAL => 5, + T_IS_NOT_IDENTICAL => 5, + T_IS_SMALLER_OR_EQUAL => 5, + T_IS_GREATER_OR_EQUAL => 5, + ]; + + /** + * Tokens that represent assignments. + * + * @var array + */ + public static $assignmentTokens = [ + T_EQUAL => T_EQUAL, + T_AND_EQUAL => T_AND_EQUAL, + T_OR_EQUAL => T_OR_EQUAL, + T_CONCAT_EQUAL => T_CONCAT_EQUAL, + T_DIV_EQUAL => T_DIV_EQUAL, + T_MINUS_EQUAL => T_MINUS_EQUAL, + T_POW_EQUAL => T_POW_EQUAL, + T_MOD_EQUAL => T_MOD_EQUAL, + T_MUL_EQUAL => T_MUL_EQUAL, + T_PLUS_EQUAL => T_PLUS_EQUAL, + T_XOR_EQUAL => T_XOR_EQUAL, + T_DOUBLE_ARROW => T_DOUBLE_ARROW, + T_SL_EQUAL => T_SL_EQUAL, + T_SR_EQUAL => T_SR_EQUAL, + T_COALESCE_EQUAL => T_COALESCE_EQUAL, + T_ZSR_EQUAL => T_ZSR_EQUAL, + ]; + + /** + * Tokens that represent equality comparisons. + * + * @var array + */ + public static $equalityTokens = [ + T_IS_EQUAL => T_IS_EQUAL, + T_IS_NOT_EQUAL => T_IS_NOT_EQUAL, + T_IS_IDENTICAL => T_IS_IDENTICAL, + T_IS_NOT_IDENTICAL => T_IS_NOT_IDENTICAL, + T_IS_SMALLER_OR_EQUAL => T_IS_SMALLER_OR_EQUAL, + T_IS_GREATER_OR_EQUAL => T_IS_GREATER_OR_EQUAL, + ]; + + /** + * Tokens that represent comparison operator. + * + * @var array + */ + public static $comparisonTokens = [ + T_IS_EQUAL => T_IS_EQUAL, + T_IS_IDENTICAL => T_IS_IDENTICAL, + T_IS_NOT_EQUAL => T_IS_NOT_EQUAL, + T_IS_NOT_IDENTICAL => T_IS_NOT_IDENTICAL, + T_LESS_THAN => T_LESS_THAN, + T_GREATER_THAN => T_GREATER_THAN, + T_IS_SMALLER_OR_EQUAL => T_IS_SMALLER_OR_EQUAL, + T_IS_GREATER_OR_EQUAL => T_IS_GREATER_OR_EQUAL, + T_SPACESHIP => T_SPACESHIP, + T_COALESCE => T_COALESCE, + ]; + + /** + * Tokens that represent arithmetic operators. + * + * @var array + */ + public static $arithmeticTokens = [ + T_PLUS => T_PLUS, + T_MINUS => T_MINUS, + T_MULTIPLY => T_MULTIPLY, + T_DIVIDE => T_DIVIDE, + T_MODULUS => T_MODULUS, + T_POW => T_POW, + ]; + + /** + * Tokens that perform operations. + * + * @var array + */ + public static $operators = [ + T_MINUS => T_MINUS, + T_PLUS => T_PLUS, + T_MULTIPLY => T_MULTIPLY, + T_DIVIDE => T_DIVIDE, + T_MODULUS => T_MODULUS, + T_POW => T_POW, + T_SPACESHIP => T_SPACESHIP, + T_COALESCE => T_COALESCE, + T_BITWISE_AND => T_BITWISE_AND, + T_BITWISE_OR => T_BITWISE_OR, + T_BITWISE_XOR => T_BITWISE_XOR, + T_SL => T_SL, + T_SR => T_SR, + ]; + + /** + * Tokens that perform boolean operations. + * + * @var array + */ + public static $booleanOperators = [ + T_BOOLEAN_AND => T_BOOLEAN_AND, + T_BOOLEAN_OR => T_BOOLEAN_OR, + T_LOGICAL_AND => T_LOGICAL_AND, + T_LOGICAL_OR => T_LOGICAL_OR, + T_LOGICAL_XOR => T_LOGICAL_XOR, + ]; + + /** + * Tokens that represent casting. + * + * @var array + */ + public static $castTokens = [ + T_INT_CAST => T_INT_CAST, + T_STRING_CAST => T_STRING_CAST, + T_DOUBLE_CAST => T_DOUBLE_CAST, + T_ARRAY_CAST => T_ARRAY_CAST, + T_BOOL_CAST => T_BOOL_CAST, + T_OBJECT_CAST => T_OBJECT_CAST, + T_UNSET_CAST => T_UNSET_CAST, + T_BINARY_CAST => T_BINARY_CAST, + ]; + + /** + * Token types that open parenthesis. + * + * @var array + */ + public static $parenthesisOpeners = [ + T_ARRAY => T_ARRAY, + T_LIST => T_LIST, + T_FUNCTION => T_FUNCTION, + T_CLOSURE => T_CLOSURE, + T_ANON_CLASS => T_ANON_CLASS, + T_WHILE => T_WHILE, + T_FOR => T_FOR, + T_FOREACH => T_FOREACH, + T_SWITCH => T_SWITCH, + T_IF => T_IF, + T_ELSEIF => T_ELSEIF, + T_CATCH => T_CATCH, + T_DECLARE => T_DECLARE, + T_MATCH => T_MATCH, + ]; + + /** + * Tokens that are allowed to open scopes. + * + * @var array + */ + public static $scopeOpeners = [ + T_CLASS => T_CLASS, + T_ANON_CLASS => T_ANON_CLASS, + T_INTERFACE => T_INTERFACE, + T_TRAIT => T_TRAIT, + T_ENUM => T_ENUM, + T_NAMESPACE => T_NAMESPACE, + T_FUNCTION => T_FUNCTION, + T_CLOSURE => T_CLOSURE, + T_IF => T_IF, + T_SWITCH => T_SWITCH, + T_CASE => T_CASE, + T_DECLARE => T_DECLARE, + T_DEFAULT => T_DEFAULT, + T_WHILE => T_WHILE, + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + T_FOR => T_FOR, + T_FOREACH => T_FOREACH, + T_DO => T_DO, + T_TRY => T_TRY, + T_CATCH => T_CATCH, + T_FINALLY => T_FINALLY, + T_PROPERTY => T_PROPERTY, + T_OBJECT => T_OBJECT, + T_USE => T_USE, + T_MATCH => T_MATCH, + ]; + + /** + * Tokens that represent scope modifiers. + * + * @var array + */ + public static $scopeModifiers = [ + T_PRIVATE => T_PRIVATE, + T_PUBLIC => T_PUBLIC, + T_PROTECTED => T_PROTECTED, + ]; + + /** + * Tokens that can prefix a method name + * + * @var array + */ + public static $methodPrefixes = [ + T_PRIVATE => T_PRIVATE, + T_PUBLIC => T_PUBLIC, + T_PROTECTED => T_PROTECTED, + T_ABSTRACT => T_ABSTRACT, + T_STATIC => T_STATIC, + T_FINAL => T_FINAL, + ]; + + /** + * Tokens that open code blocks. + * + * @var array + */ + public static $blockOpeners = [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_OPEN_SQUARE_BRACKET => T_OPEN_SQUARE_BRACKET, + T_OPEN_PARENTHESIS => T_OPEN_PARENTHESIS, + T_OBJECT => T_OBJECT, + ]; + + /** + * Tokens that don't represent code. + * + * @var array + */ + public static $emptyTokens = [ + T_WHITESPACE => T_WHITESPACE, + T_COMMENT => T_COMMENT, + T_DOC_COMMENT => T_DOC_COMMENT, + T_DOC_COMMENT_STAR => T_DOC_COMMENT_STAR, + T_DOC_COMMENT_WHITESPACE => T_DOC_COMMENT_WHITESPACE, + T_DOC_COMMENT_TAG => T_DOC_COMMENT_TAG, + T_DOC_COMMENT_OPEN_TAG => T_DOC_COMMENT_OPEN_TAG, + T_DOC_COMMENT_CLOSE_TAG => T_DOC_COMMENT_CLOSE_TAG, + T_DOC_COMMENT_STRING => T_DOC_COMMENT_STRING, + T_PHPCS_ENABLE => T_PHPCS_ENABLE, + T_PHPCS_DISABLE => T_PHPCS_DISABLE, + T_PHPCS_SET => T_PHPCS_SET, + T_PHPCS_IGNORE => T_PHPCS_IGNORE, + T_PHPCS_IGNORE_FILE => T_PHPCS_IGNORE_FILE, + ]; + + /** + * Tokens that are comments. + * + * @var array + */ + public static $commentTokens = [ + T_COMMENT => T_COMMENT, + T_DOC_COMMENT => T_DOC_COMMENT, + T_DOC_COMMENT_STAR => T_DOC_COMMENT_STAR, + T_DOC_COMMENT_WHITESPACE => T_DOC_COMMENT_WHITESPACE, + T_DOC_COMMENT_TAG => T_DOC_COMMENT_TAG, + T_DOC_COMMENT_OPEN_TAG => T_DOC_COMMENT_OPEN_TAG, + T_DOC_COMMENT_CLOSE_TAG => T_DOC_COMMENT_CLOSE_TAG, + T_DOC_COMMENT_STRING => T_DOC_COMMENT_STRING, + T_PHPCS_ENABLE => T_PHPCS_ENABLE, + T_PHPCS_DISABLE => T_PHPCS_DISABLE, + T_PHPCS_SET => T_PHPCS_SET, + T_PHPCS_IGNORE => T_PHPCS_IGNORE, + T_PHPCS_IGNORE_FILE => T_PHPCS_IGNORE_FILE, + ]; + + /** + * Tokens that are comments containing PHPCS instructions. + * + * @var array + */ + public static $phpcsCommentTokens = [ + T_PHPCS_ENABLE => T_PHPCS_ENABLE, + T_PHPCS_DISABLE => T_PHPCS_DISABLE, + T_PHPCS_SET => T_PHPCS_SET, + T_PHPCS_IGNORE => T_PHPCS_IGNORE, + T_PHPCS_IGNORE_FILE => T_PHPCS_IGNORE_FILE, + ]; + + /** + * Tokens that represent strings. + * + * Note that T_STRINGS are NOT represented in this list. + * + * @var array + */ + public static $stringTokens = [ + T_CONSTANT_ENCAPSED_STRING => T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING => T_DOUBLE_QUOTED_STRING, + ]; + + /** + * Tokens that represent text strings. + * + * @var array + */ + public static $textStringTokens = [ + T_CONSTANT_ENCAPSED_STRING => T_CONSTANT_ENCAPSED_STRING, + T_DOUBLE_QUOTED_STRING => T_DOUBLE_QUOTED_STRING, + T_INLINE_HTML => T_INLINE_HTML, + T_HEREDOC => T_HEREDOC, + T_NOWDOC => T_NOWDOC, + ]; + + /** + * Tokens that represent brackets and parenthesis. + * + * @var array + */ + public static $bracketTokens = [ + T_OPEN_CURLY_BRACKET => T_OPEN_CURLY_BRACKET, + T_CLOSE_CURLY_BRACKET => T_CLOSE_CURLY_BRACKET, + T_OPEN_SQUARE_BRACKET => T_OPEN_SQUARE_BRACKET, + T_CLOSE_SQUARE_BRACKET => T_CLOSE_SQUARE_BRACKET, + T_OPEN_PARENTHESIS => T_OPEN_PARENTHESIS, + T_CLOSE_PARENTHESIS => T_CLOSE_PARENTHESIS, + ]; + + /** + * Tokens that include files. + * + * @var array + */ + public static $includeTokens = [ + T_REQUIRE_ONCE => T_REQUIRE_ONCE, + T_REQUIRE => T_REQUIRE, + T_INCLUDE_ONCE => T_INCLUDE_ONCE, + T_INCLUDE => T_INCLUDE, + ]; + + /** + * Tokens that make up a heredoc string. + * + * @var array + */ + public static $heredocTokens = [ + T_START_HEREDOC => T_START_HEREDOC, + T_END_HEREDOC => T_END_HEREDOC, + T_HEREDOC => T_HEREDOC, + T_START_NOWDOC => T_START_NOWDOC, + T_END_NOWDOC => T_END_NOWDOC, + T_NOWDOC => T_NOWDOC, + ]; + + /** + * Tokens that represent the names of called functions. + * + * Mostly, these are just strings. But PHP tokenizes some language + * constructs and functions using their own tokens. + * + * @var array + */ + public static $functionNameTokens = [ + T_STRING => T_STRING, + T_EVAL => T_EVAL, + T_EXIT => T_EXIT, + T_INCLUDE => T_INCLUDE, + T_INCLUDE_ONCE => T_INCLUDE_ONCE, + T_REQUIRE => T_REQUIRE, + T_REQUIRE_ONCE => T_REQUIRE_ONCE, + T_ISSET => T_ISSET, + T_UNSET => T_UNSET, + T_EMPTY => T_EMPTY, + T_SELF => T_SELF, + T_PARENT => T_PARENT, + T_STATIC => T_STATIC, + ]; + + /** + * Tokens that open class and object scopes. + * + * @var array + */ + public static $ooScopeTokens = [ + T_CLASS => T_CLASS, + T_ANON_CLASS => T_ANON_CLASS, + T_INTERFACE => T_INTERFACE, + T_TRAIT => T_TRAIT, + T_ENUM => T_ENUM, + ]; + + /** + * Tokens representing PHP magic constants. + * + * @var array => + * + * @link https://www.php.net/language.constants.predefined PHP Manual on magic constants + */ + public static $magicConstants = [ + T_CLASS_C => T_CLASS_C, + T_DIR => T_DIR, + T_FILE => T_FILE, + T_FUNC_C => T_FUNC_C, + T_LINE => T_LINE, + T_METHOD_C => T_METHOD_C, + T_NS_C => T_NS_C, + T_TRAIT_C => T_TRAIT_C, + ]; + + /** + * Tokens representing context sensitive keywords in PHP. + * + * @var array + * + * https://wiki.php.net/rfc/context_sensitive_lexer + */ + public static $contextSensitiveKeywords = [ + T_ABSTRACT => T_ABSTRACT, + T_ARRAY => T_ARRAY, + T_AS => T_AS, + T_BREAK => T_BREAK, + T_CALLABLE => T_CALLABLE, + T_CASE => T_CASE, + T_CATCH => T_CATCH, + T_CLASS => T_CLASS, + T_CLONE => T_CLONE, + T_CONST => T_CONST, + T_CONTINUE => T_CONTINUE, + T_DECLARE => T_DECLARE, + T_DEFAULT => T_DEFAULT, + T_DO => T_DO, + T_ECHO => T_ECHO, + T_ELSE => T_ELSE, + T_ELSEIF => T_ELSEIF, + T_EMPTY => T_EMPTY, + T_ENDDECLARE => T_ENDDECLARE, + T_ENDFOR => T_ENDFOR, + T_ENDFOREACH => T_ENDFOREACH, + T_ENDIF => T_ENDIF, + T_ENDSWITCH => T_ENDSWITCH, + T_ENDWHILE => T_ENDWHILE, + T_ENUM => T_ENUM, + T_EVAL => T_EVAL, + T_EXIT => T_EXIT, + T_EXTENDS => T_EXTENDS, + T_FINAL => T_FINAL, + T_FINALLY => T_FINALLY, + T_FN => T_FN, + T_FOR => T_FOR, + T_FOREACH => T_FOREACH, + T_FUNCTION => T_FUNCTION, + T_GLOBAL => T_GLOBAL, + T_GOTO => T_GOTO, + T_IF => T_IF, + T_IMPLEMENTS => T_IMPLEMENTS, + T_INCLUDE => T_INCLUDE, + T_INCLUDE_ONCE => T_INCLUDE_ONCE, + T_INSTANCEOF => T_INSTANCEOF, + T_INSTEADOF => T_INSTEADOF, + T_INTERFACE => T_INTERFACE, + T_ISSET => T_ISSET, + T_LIST => T_LIST, + T_LOGICAL_AND => T_LOGICAL_AND, + T_LOGICAL_OR => T_LOGICAL_OR, + T_LOGICAL_XOR => T_LOGICAL_XOR, + T_MATCH => T_MATCH, + T_NAMESPACE => T_NAMESPACE, + T_NEW => T_NEW, + T_PRINT => T_PRINT, + T_PRIVATE => T_PRIVATE, + T_PROTECTED => T_PROTECTED, + T_PUBLIC => T_PUBLIC, + T_READONLY => T_READONLY, + T_REQUIRE => T_REQUIRE, + T_REQUIRE_ONCE => T_REQUIRE_ONCE, + T_RETURN => T_RETURN, + T_STATIC => T_STATIC, + T_SWITCH => T_SWITCH, + T_THROW => T_THROW, + T_TRAIT => T_TRAIT, + T_TRY => T_TRY, + T_UNSET => T_UNSET, + T_USE => T_USE, + T_VAR => T_VAR, + T_WHILE => T_WHILE, + T_YIELD => T_YIELD, + T_YIELD_FROM => T_YIELD_FROM, + ]; + + + /** + * Given a token, returns the name of the token. + * + * If passed an integer, the token name is sourced from PHP's token_name() + * function. If passed a string, it is assumed to be a PHPCS-supplied token + * that begins with PHPCS_T_, so the name is sourced from the token value itself. + * + * @param int|string $token The token to get the name for. + * + * @return string + */ + public static function tokenName($token) + { + if (is_string($token) === false) { + // PHP-supplied token name. + return token_name($token); + } + + return substr($token, 6); + + }//end tokenName() + + + /** + * Returns the highest weighted token type. + * + * Tokens are weighted by their approximate frequency of appearance in code + * - the less frequently they appear in the code, the higher the weighting. + * For example T_CLASS tokens appear very infrequently in a file, and + * therefore have a high weighting. + * + * Returns false if there are no weightings for any of the specified tokens. + * + * @param array $tokens The token types to get the highest weighted + * type for. + * + * @return int|false The highest weighted token. + */ + public static function getHighestWeightedToken(array $tokens) + { + $highest = -1; + $highestType = false; + + $weights = self::$weightings; + + foreach ($tokens as $token) { + if (isset($weights[$token]) === true) { + $weight = $weights[$token]; + } else { + $weight = 0; + } + + if ($weight > $highest) { + $highest = $weight; + $highestType = $token; + } + } + + return $highestType; + + }//end getHighestWeightedToken() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/AllTests.php b/vendor/squizlabs/php_codesniffer/tests/AllTests.php new file mode 100644 index 0000000..4fa41d9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/AllTests.php @@ -0,0 +1,58 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests; + +require_once 'Core/AllTests.php'; +require_once 'Standards/AllSniffs.php'; + +// PHPUnit 7 made the TestSuite run() method incompatible with +// older PHPUnit versions due to return type hints, so maintain +// two different suite objects. +$phpunit7 = false; +if (class_exists('\PHPUnit\Runner\Version') === true) { + $version = \PHPUnit\Runner\Version::id(); + if (version_compare($version, '7.0', '>=') === true) { + $phpunit7 = true; + } +} + +if ($phpunit7 === true) { + include_once 'TestSuite7.php'; +} else { + include_once 'TestSuite.php'; +} + +class PHP_CodeSniffer_AllTests +{ + + + /** + * Add all PHP_CodeSniffer test suites into a single test suite. + * + * @return \PHPUnit\Framework\TestSuite + */ + public static function suite() + { + $GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'] = []; + $GLOBALS['PHP_CODESNIFFER_TEST_DIRS'] = []; + + // Use a special PHP_CodeSniffer test suite so that we can + // unset our autoload function after the run. + $suite = new TestSuite('PHP CodeSniffer'); + + $suite->addTest(Core\AllTests::suite()); + $suite->addTest(Standards\AllSniffs::suite()); + + return $suite; + + }//end suite() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/AbstractMethodUnitTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/AbstractMethodUnitTest.php new file mode 100644 index 0000000..abab2d6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/AbstractMethodUnitTest.php @@ -0,0 +1,218 @@ + + * @copyright 2018-2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Files\DummyFile; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; + +abstract class AbstractMethodUnitTest extends TestCase +{ + + /** + * The file extension of the test case file (without leading dot). + * + * This allows child classes to overrule the default `inc` with, for instance, + * `js` or `css` when applicable. + * + * @var string + */ + protected static $fileExtension = 'inc'; + + /** + * The tab width setting to use when tokenizing the file. + * + * This allows for test case files to use a different tab width than the default. + * + * @var integer + */ + protected static $tabWidth = 4; + + /** + * The \PHP_CodeSniffer\Files\File object containing the parsed contents of the test case file. + * + * @var \PHP_CodeSniffer\Files\File + */ + protected static $phpcsFile; + + + /** + * Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file. + * + * The test case file for a unit test class has to be in the same directory + * directory and use the same file name as the test class, using the .inc extension. + * + * @beforeClass + * + * @return void + */ + public static function initializeFile() + { + /* + * Set the static properties in the Config class to specific values for performance + * and to clear out values from other tests. + */ + + self::setStaticConfigProperty('executablePaths', []); + + // Set to a usable value to circumvent Config trying to find a phpcs.xml config file. + self::setStaticConfigProperty('overriddenDefaults', ['standards' => ['PSR1']]); + + // Set to values which prevent the test-runner user's `CodeSniffer.conf` file + // from being read and influencing the tests. Also prevent an `exec()` call to stty. + self::setStaticConfigProperty('configData', ['report_width' => 80]); + self::setStaticConfigProperty('configDataFile', ''); + + $config = new Config(); + // Also set a tab-width to enable testing tab-replaced vs `orig_content`. + $config->tabWidth = static::$tabWidth; + + $ruleset = new Ruleset($config); + + // Default to a file with the same name as the test class. Extension is property based. + $relativeCN = str_replace(__NAMESPACE__, '', get_called_class()); + $relativePath = str_replace('\\', DIRECTORY_SEPARATOR, $relativeCN); + $pathToTestFile = realpath(__DIR__).$relativePath.'.'.static::$fileExtension; + + // Make sure the file gets parsed correctly based on the file type. + $contents = 'phpcs_input_file: '.$pathToTestFile.PHP_EOL; + $contents .= file_get_contents($pathToTestFile); + + self::$phpcsFile = new DummyFile($contents, $ruleset, $config); + self::$phpcsFile->process(); + + }//end initializeFile() + + + /** + * Clean up after finished test. + * + * @afterClass + * + * @return void + */ + public static function resetFile() + { + self::$phpcsFile = null; + + // Reset the static properties in the Config class to their defaults to prevent tests influencing each other. + self::setStaticConfigProperty('overriddenDefaults', []); + self::setStaticConfigProperty('executablePaths', []); + self::setStaticConfigProperty('configData', null); + self::setStaticConfigProperty('configDataFile', null); + + }//end resetFile() + + + /** + * Helper function to set the value of a private static property on the Config class. + * + * @param string $name The name of the property to set. + * @param mixed $value The value to set the property to. + * + * @return void + */ + public static function setStaticConfigProperty($name, $value) + { + $property = new ReflectionProperty('PHP_CodeSniffer\Config', $name); + $property->setAccessible(true); + $property->setValue(null, $value); + $property->setAccessible(false); + + }//end setStaticConfigProperty() + + + /** + * Get the token pointer for a target token based on a specific comment found on the line before. + * + * Note: the test delimiter comment MUST start with "/* test" to allow this function to + * distinguish between comments used *in* a test and test delimiters. + * + * @param string $commentString The delimiter comment to look for. + * @param int|string|array $tokenType The type of token(s) to look for. + * @param string $tokenContent Optional. The token content for the target token. + * + * @return int + */ + public function getTargetToken($commentString, $tokenType, $tokenContent=null) + { + $start = (self::$phpcsFile->numTokens - 1); + $comment = self::$phpcsFile->findPrevious( + T_COMMENT, + $start, + null, + false, + $commentString + ); + + $tokens = self::$phpcsFile->getTokens(); + $end = ($start + 1); + + // Limit the token finding to between this and the next delimiter comment. + for ($i = ($comment + 1); $i < $end; $i++) { + if ($tokens[$i]['code'] !== T_COMMENT) { + continue; + } + + if (stripos($tokens[$i]['content'], '/* test') === 0) { + $end = $i; + break; + } + } + + $target = self::$phpcsFile->findNext( + $tokenType, + ($comment + 1), + $end, + false, + $tokenContent + ); + + if ($target === false) { + $msg = 'Failed to find test target token for comment string: '.$commentString; + if ($tokenContent !== null) { + $msg .= ' With token content: '.$tokenContent; + } + + $this->assertFalse(true, $msg); + } + + return $target; + + }//end getTargetToken() + + + /** + * Helper method to tell PHPUnit to expect a PHPCS RuntimeException in a PHPUnit cross-version + * compatible manner. + * + * @param string $message The expected exception message. + * + * @return void + */ + public function expectRunTimeException($message) + { + $exception = 'PHP_CodeSniffer\Exceptions\RuntimeException'; + + if (method_exists($this, 'expectException') === true) { + // PHPUnit 5+. + $this->expectException($exception); + $this->expectExceptionMessage($message); + } else { + // PHPUnit 4. + $this->setExpectedException($exception, $message); + } + + }//end expectRunTimeException() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/AllTests.php b/vendor/squizlabs/php_codesniffer/tests/Core/AllTests.php new file mode 100644 index 0000000..60547bb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/AllTests.php @@ -0,0 +1,63 @@ + + * @author Juliette Reinders Folmer + * @copyright 2006-2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core; + +use PHP_CodeSniffer\Tests\FileList; +use PHPUnit\TextUI\TestRunner; +use PHPUnit\Framework\TestSuite; + +class AllTests +{ + + + /** + * Prepare the test runner. + * + * @return void + */ + public static function main() + { + TestRunner::run(self::suite()); + + }//end main() + + + /** + * Add all core unit tests into a test suite. + * + * @return \PHPUnit\Framework\TestSuite + */ + public static function suite() + { + $suite = new TestSuite('PHP CodeSniffer Core'); + + $testFileIterator = new FileList(__DIR__, '', '`Test\.php$`Di'); + foreach ($testFileIterator->fileIterator as $file) { + if (strpos($file, 'AbstractMethodUnitTest.php') !== false) { + continue; + } + + include_once $file; + + $class = str_replace(__DIR__, '', $file); + $class = str_replace('.php', '', $class); + $class = str_replace('/', '\\', $class); + $class = 'PHP_CodeSniffer\Tests\Core'.$class; + + $suite->addTestSuite($class); + } + + return $suite; + + }//end suite() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/DetermineLoadedClassTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/DetermineLoadedClassTest.php new file mode 100644 index 0000000..44a4cef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/DetermineLoadedClassTest.php @@ -0,0 +1,126 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Autoloader; + +use PHP_CodeSniffer\Autoload; +use PHPUnit\Framework\TestCase; + +/** + * Tests for the \PHP_CodeSniffer\Autoload::determineLoadedClass method. + * + * @covers \PHP_CodeSniffer\Autoload::determineLoadedClass + */ +class DetermineLoadedClassTest extends TestCase +{ + + + /** + * Load the test files. + * + * @beforeClass + * + * @return void + */ + public static function includeFixture() + { + include __DIR__.'/TestFiles/Sub/C.inc'; + + }//end includeFixture() + + + /** + * Test for when class list is ordered. + * + * @return void + */ + public function testOrdered() + { + $classesBeforeLoad = [ + 'classes' => [], + 'interfaces' => [], + 'traits' => [], + ]; + + $classesAfterLoad = [ + 'classes' => [ + 'PHP_CodeSniffer\Tests\Core\Autoloader\A', + 'PHP_CodeSniffer\Tests\Core\Autoloader\B', + 'PHP_CodeSniffer\Tests\Core\Autoloader\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', + ], + 'interfaces' => [], + 'traits' => [], + ]; + + $className = Autoload::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + $this->assertEquals('PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', $className); + + }//end testOrdered() + + + /** + * Test for when class list is out of order. + * + * @return void + */ + public function testUnordered() + { + $classesBeforeLoad = [ + 'classes' => [], + 'interfaces' => [], + 'traits' => [], + ]; + + $classesAfterLoad = [ + 'classes' => [ + 'PHP_CodeSniffer\Tests\Core\Autoloader\A', + 'PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\B', + ], + 'interfaces' => [], + 'traits' => [], + ]; + + $className = Autoload::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + $this->assertEquals('PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', $className); + + $classesAfterLoad = [ + 'classes' => [ + 'PHP_CodeSniffer\Tests\Core\Autoloader\A', + 'PHP_CodeSniffer\Tests\Core\Autoloader\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\B', + ], + 'interfaces' => [], + 'traits' => [], + ]; + + $className = Autoload::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + $this->assertEquals('PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', $className); + + $classesAfterLoad = [ + 'classes' => [ + 'PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\A', + 'PHP_CodeSniffer\Tests\Core\Autoloader\C', + 'PHP_CodeSniffer\Tests\Core\Autoloader\B', + ], + 'interfaces' => [], + 'traits' => [], + ]; + + $className = Autoload::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + $this->assertEquals('PHP_CodeSniffer\Tests\Core\Autoloader\Sub\C', $className); + + }//end testUnordered() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/TestFiles/A.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/TestFiles/A.inc new file mode 100644 index 0000000..c143371 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Autoloader/TestFiles/A.inc @@ -0,0 +1,3 @@ + + * @copyright 2006-2023 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Config; + +use PHP_CodeSniffer\Config; +use PHPUnit\Framework\TestCase; +use ReflectionProperty; + +/** + * Tests for the \PHP_CodeSniffer\Config reportWidth value. + * + * @covers \PHP_CodeSniffer\Config::__get + */ +class ReportWidthTest extends TestCase +{ + + + /** + * Set static properties in the Config class to prevent tests influencing each other. + * + * @before + * + * @return void + */ + public static function cleanConfig() + { + // Set to the property's default value to clear out potentially set values from other tests. + self::setStaticProperty('executablePaths', []); + + // Set to a usable value to circumvent Config trying to find a phpcs.xml config file. + self::setStaticProperty('overriddenDefaults', ['standards' => ['PSR1']]); + + // Set to values which prevent the test-runner user's `CodeSniffer.conf` file + // from being read and influencing the tests. + self::setStaticProperty('configData', []); + self::setStaticProperty('configDataFile', ''); + + }//end cleanConfig() + + + /** + * Clean up after each finished test. + * + * @after + * + * @return void + */ + public function resetConfig() + { + $_SERVER['argv'] = []; + + }//end resetConfig() + + + /** + * Reset the static properties in the Config class to their true defaults to prevent this class + * from influencing other tests. + * + * @afterClass + * + * @return void + */ + public static function resetConfigToDefaults() + { + self::setStaticProperty('overriddenDefaults', []); + self::setStaticProperty('executablePaths', []); + self::setStaticProperty('configData', null); + self::setStaticProperty('configDataFile', null); + $_SERVER['argv'] = []; + + }//end resetConfigToDefaults() + + + /** + * Test that report width without overrules will always be set to a non-0 positive integer. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::restoreDefaults + * + * @return void + */ + public function testReportWidthDefault() + { + $config = new Config(); + + // Can't test the exact value as "auto" will resolve differently depending on the machine running the tests. + $this->assertTrue(is_int($config->reportWidth), 'Report width is not an integer'); + $this->assertGreaterThan(0, $config->reportWidth, 'Report width is not greater than 0'); + + }//end testReportWidthDefault() + + + /** + * Test that the report width will be set to a non-0 positive integer when not found in the CodeSniffer.conf file. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::restoreDefaults + * + * @return void + */ + public function testReportWidthWillBeSetFromAutoWhenNotFoundInConfFile() + { + $phpCodeSnifferConfig = [ + 'default_standard' => 'PSR2', + 'show_warnings' => '0', + ]; + + $this->setStaticProperty('configData', $phpCodeSnifferConfig); + + $config = new Config(); + + // Can't test the exact value as "auto" will resolve differently depending on the machine running the tests. + $this->assertTrue(is_int($config->reportWidth), 'Report width is not an integer'); + $this->assertGreaterThan(0, $config->reportWidth, 'Report width is not greater than 0'); + + }//end testReportWidthWillBeSetFromAutoWhenNotFoundInConfFile() + + + /** + * Test that the report width will be set correctly when found in the CodeSniffer.conf file. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::getConfigData + * @covers \PHP_CodeSniffer\Config::restoreDefaults + * + * @return void + */ + public function testReportWidthCanBeSetFromConfFile() + { + $phpCodeSnifferConfig = [ + 'default_standard' => 'PSR2', + 'report_width' => '120', + ]; + + $this->setStaticProperty('configData', $phpCodeSnifferConfig); + + $config = new Config(); + $this->assertSame(120, $config->reportWidth); + + }//end testReportWidthCanBeSetFromConfFile() + + + /** + * Test that the report width will be set correctly when passed as a CLI argument. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::processLongArgument + * + * @return void + */ + public function testReportWidthCanBeSetFromCLI() + { + $_SERVER['argv'] = [ + 'phpcs', + '--report-width=100', + ]; + + $config = new Config(); + $this->assertSame(100, $config->reportWidth); + + }//end testReportWidthCanBeSetFromCLI() + + + /** + * Test that the report width will be set correctly when multiple report widths are passed on the CLI. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::processLongArgument + * + * @return void + */ + public function testReportWidthWhenSetFromCLIFirstValuePrevails() + { + $_SERVER['argv'] = [ + 'phpcs', + '--report-width=100', + '--report-width=200', + ]; + + $config = new Config(); + $this->assertSame(100, $config->reportWidth); + + }//end testReportWidthWhenSetFromCLIFirstValuePrevails() + + + /** + * Test that a report width passed as a CLI argument will overrule a report width set in a CodeSniffer.conf file. + * + * @covers \PHP_CodeSniffer\Config::__set + * @covers \PHP_CodeSniffer\Config::processLongArgument + * @covers \PHP_CodeSniffer\Config::getConfigData + * + * @return void + */ + public function testReportWidthSetFromCLIOverrulesConfFile() + { + $phpCodeSnifferConfig = [ + 'default_standard' => 'PSR2', + 'report_format' => 'summary', + 'show_warnings' => '0', + 'show_progress' => '1', + 'report_width' => '120', + ]; + + $this->setStaticProperty('configData', $phpCodeSnifferConfig); + + $cliArgs = [ + 'phpcs', + '--report-width=180', + ]; + + $config = new Config($cliArgs); + $this->assertSame(180, $config->reportWidth); + + }//end testReportWidthSetFromCLIOverrulesConfFile() + + + /** + * Test that the report width will be set to a non-0 positive integer when set to "auto". + * + * @covers \PHP_CodeSniffer\Config::__set + * + * @return void + */ + public function testReportWidthInputHandlingForAuto() + { + $config = new Config(); + $config->reportWidth = 'auto'; + + // Can't test the exact value as "auto" will resolve differently depending on the machine running the tests. + $this->assertTrue(is_int($config->reportWidth), 'Report width is not an integer'); + $this->assertGreaterThan(0, $config->reportWidth, 'Report width is not greater than 0'); + + }//end testReportWidthInputHandlingForAuto() + + + /** + * Test that the report width will be set correctly for various types of input. + * + * @param mixed $input Input value received. + * @param int $expected Expected report width. + * + * @dataProvider dataReportWidthInputHandling + * @covers \PHP_CodeSniffer\Config::__set + * + * @return void + */ + public function testReportWidthInputHandling($input, $expected) + { + $config = new Config(); + $config->reportWidth = $input; + + $this->assertSame($expected, $config->reportWidth); + + }//end testReportWidthInputHandling() + + + /** + * Data provider. + * + * @return array + */ + public function dataReportWidthInputHandling() + { + return [ + 'No value (empty string)' => [ + 'value' => '', + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: invalid input type null' => [ + 'value' => null, + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: invalid input type false' => [ + 'value' => false, + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: invalid input type float' => [ + 'value' => 100.50, + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: invalid string value "invalid"' => [ + 'value' => 'invalid', + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: invalid string value, non-integer string "50.25"' => [ + 'value' => '50.25', + 'expected' => Config::DEFAULT_REPORT_WIDTH, + ], + 'Value: valid numeric string value' => [ + 'value' => '250', + 'expected' => 250, + ], + 'Value: valid int value' => [ + 'value' => 220, + 'expected' => 220, + ], + 'Value: negative int value becomes positive int' => [ + 'value' => -180, + 'expected' => 180, + ], + ]; + + }//end dataReportWidthInputHandling() + + + /** + * Helper function to set a static property on the Config class. + * + * @param string $name The name of the property to set. + * @param mixed $value The value to set the property to. + * + * @return void + */ + public static function setStaticProperty($name, $value) + { + $property = new ReflectionProperty('PHP_CodeSniffer\Config', $name); + $property->setAccessible(true); + $property->setValue(null, $value); + $property->setAccessible(false); + + }//end setStaticProperty() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/ErrorSuppressionTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/ErrorSuppressionTest.php new file mode 100644 index 0000000..7fc28d0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/ErrorSuppressionTest.php @@ -0,0 +1,1252 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Files\DummyFile; +use PHPUnit\Framework\TestCase; + +/** + * Tests for PHP_CodeSniffer error suppression tags. + * + * @coversNothing + */ +class ErrorSuppressionTest extends TestCase +{ + + + /** + * Test suppressing a single error. + * + * @param string $before Annotation to place before the code. + * @param string $after Annotation to place after the code. + * @param int $expectedErrors Optional. Number of errors expected. + * Defaults to 0. + * + * @dataProvider dataSuppressError + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressError($before, $after, $expectedErrors=0) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.PHP.LowerCaseConstant']; + + $ruleset = new Ruleset($config); + } + + $content = 'process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + }//end testSuppressError() + + + /** + * Data provider. + * + * @see testSuppressError() + * + * @return array + */ + public function dataSuppressError() + { + return [ + 'no suppression' => [ + 'before' => '', + 'after' => '', + 'expectedErrors' => 1, + ], + + // Inline slash comments. + 'disable/enable: slash comment' => [ + 'before' => '// phpcs:disable'.PHP_EOL, + 'after' => '// phpcs:enable', + ], + 'disable/enable: multi-line slash comment, tab indented' => [ + 'before' => "\t".'// For reasons'.PHP_EOL."\t".'// phpcs:disable'.PHP_EOL."\t", + 'after' => "\t".'// phpcs:enable', + ], + 'disable/enable: slash comment, with @' => [ + 'before' => '// @phpcs:disable'.PHP_EOL, + 'after' => '// @phpcs:enable', + ], + 'disable/enable: slash comment, mixed case' => [ + 'before' => '// PHPCS:Disable'.PHP_EOL, + 'after' => '// pHPcs:enabLE', + ], + + // Inline hash comments. + 'disable/enable: hash comment' => [ + 'before' => '# phpcs:disable'.PHP_EOL, + 'after' => '# phpcs:enable', + ], + 'disable/enable: multi-line hash comment, tab indented' => [ + 'before' => "\t".'# For reasons'.PHP_EOL."\t".'# phpcs:disable'.PHP_EOL."\t", + 'after' => "\t".'# phpcs:enable', + ], + 'disable/enable: hash comment, with @' => [ + 'before' => '# @phpcs:disable'.PHP_EOL, + 'after' => '# @phpcs:enable', + ], + 'disable/enable: hash comment, mixed case' => [ + 'before' => '# PHPCS:Disable'.PHP_EOL, + 'after' => '# pHPcs:enabLE', + ], + + // Inline star (block) comments. + 'disable/enable: star comment' => [ + 'before' => '/* phpcs:disable */'.PHP_EOL, + 'after' => '/* phpcs:enable */', + ], + 'disable/enable: multi-line star comment' => [ + 'before' => '/*'.PHP_EOL.' phpcs:disable'.PHP_EOL.' */'.PHP_EOL, + 'after' => '/*'.PHP_EOL.' phpcs:enable'.PHP_EOL.' */', + ], + 'disable/enable: multi-line star comment, each line starred' => [ + 'before' => '/*'.PHP_EOL.' * phpcs:disable'.PHP_EOL.' */'.PHP_EOL, + 'after' => '/*'.PHP_EOL.' * phpcs:enable'.PHP_EOL.' */', + ], + 'disable/enable: multi-line star comment, each line starred, tab indented' => [ + 'before' => "\t".'/*'.PHP_EOL."\t".' * phpcs:disable'.PHP_EOL."\t".' */'.PHP_EOL."\t", + 'after' => "\t".'/*'.PHP_EOL.' * phpcs:enable'.PHP_EOL.' */', + ], + + // Docblock comments. + 'disable/enable: single line docblock comment' => [ + 'before' => '/** phpcs:disable */'.PHP_EOL, + 'after' => '/** phpcs:enable */', + ], + + // Deprecated syntax. + 'old style: slash comment' => [ + 'before' => '// @codingStandardsIgnoreStart'.PHP_EOL, + 'after' => '// @codingStandardsIgnoreEnd', + ], + 'old style: star comment' => [ + 'before' => '/* @codingStandardsIgnoreStart */'.PHP_EOL, + 'after' => '/* @codingStandardsIgnoreEnd */', + ], + 'old style: multi-line star comment' => [ + 'before' => '/*'.PHP_EOL.' @codingStandardsIgnoreStart'.PHP_EOL.' */'.PHP_EOL, + 'after' => '/*'.PHP_EOL.' @codingStandardsIgnoreEnd'.PHP_EOL.' */', + ], + 'old style: single line docblock comment' => [ + 'before' => '/** @codingStandardsIgnoreStart */'.PHP_EOL, + 'after' => '/** @codingStandardsIgnoreEnd */', + ], + ]; + + }//end dataSuppressError() + + + /** + * Test suppressing 1 out of 2 errors. + * + * @param string $before Annotation to place before the code. + * @param string $between Annotation to place between the code. + * @param int $expectedErrors Optional. Number of errors expected. + * Defaults to 1. + * + * @dataProvider dataSuppressSomeErrors + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressSomeErrors($before, $between, $expectedErrors=1) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.PHP.LowerCaseConstant']; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + }//end testSuppressSomeErrors() + + + /** + * Data provider. + * + * @see testSuppressSomeErrors() + * + * @return array + */ + public function dataSuppressSomeErrors() + { + return [ + 'no suppression' => [ + 'before' => '', + 'between' => '', + 'expectedErrors' => 2, + ], + + // With suppression. + 'disable/enable: slash comment' => [ + 'before' => '// phpcs:disable', + 'between' => '// phpcs:enable', + ], + 'disable/enable: slash comment, with @' => [ + 'before' => '// @phpcs:disable', + 'between' => '// @phpcs:enable', + ], + 'disable/enable: hash comment' => [ + 'before' => '# phpcs:disable', + 'between' => '# phpcs:enable', + ], + 'disable/enable: hash comment, with @' => [ + 'before' => '# @phpcs:disable', + 'between' => '# @phpcs:enable', + ], + 'disable/enable: single line docblock comment' => [ + 'before' => '/** phpcs:disable */', + 'between' => '/** phpcs:enable */', + ], + + // Deprecated syntax. + 'old style: slash comment' => [ + 'before' => '// @codingStandardsIgnoreStart', + 'between' => '// @codingStandardsIgnoreEnd', + ], + 'old style: single line docblock comment' => [ + 'before' => '/** @codingStandardsIgnoreStart */', + 'between' => '/** @codingStandardsIgnoreEnd */', + ], + ]; + + }//end dataSuppressSomeErrors() + + + /** + * Test suppressing a single warning. + * + * @param string $before Annotation to place before the code. + * @param string $after Annotation to place after the code. + * @param int $expectedWarnings Optional. Number of warnings expected. + * Defaults to 0. + * + * @dataProvider dataSuppressWarning + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressWarning($before, $after, $expectedWarnings=0) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.Commenting.Todo']; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testSuppressWarning() + + + /** + * Data provider. + * + * @see testSuppressWarning() + * + * @return array + */ + public function dataSuppressWarning() + { + return [ + 'no suppression' => [ + 'before' => '', + 'after' => '', + 'expectedWarnings' => 1, + ], + + // With suppression. + 'disable/enable: slash comment' => [ + 'before' => '// phpcs:disable', + 'after' => '// phpcs:enable', + ], + 'disable/enable: slash comment, with @' => [ + 'before' => '// @phpcs:disable', + 'after' => '// @phpcs:enable', + ], + 'disable/enable: single line docblock comment' => [ + 'before' => '/** phpcs:disable */', + 'after' => '/** phpcs:enable */', + ], + + // Deprecated syntax. + 'old style: slash comment' => [ + 'before' => '// @codingStandardsIgnoreStart', + 'after' => '// @codingStandardsIgnoreEnd', + ], + 'old style: single line docblock comment' => [ + 'before' => '/** @codingStandardsIgnoreStart */', + 'after' => '/** @codingStandardsIgnoreEnd */', + ], + ]; + + }//end dataSuppressWarning() + + + /** + * Test suppressing a single error using a single line ignore. + * + * @param string $before Annotation to place before the code. + * @param string $after Optional. Annotation to place after the code. + * Defaults to an empty string. + * @param int $expectedErrors Optional. Number of errors expected. + * Defaults to 1. + * + * @dataProvider dataSuppressLine + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressLine($before, $after='', $expectedErrors=1) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.PHP.LowerCaseConstant']; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + }//end testSuppressLine() + + + /** + * Data provider. + * + * @see testSuppressLine() + * + * @return array + */ + public function dataSuppressLine() + { + return [ + 'no suppression' => [ + 'before' => '', + 'after' => '', + 'expectedErrors' => 2, + ], + + // With suppression on line before. + 'ignore: line before, slash comment' => ['before' => '// phpcs:ignore'], + 'ignore: line before, slash comment, with @' => ['before' => '// @phpcs:ignore'], + 'ignore: line before, hash comment' => ['before' => '# phpcs:ignore'], + 'ignore: line before, hash comment, with @' => ['before' => '# @phpcs:ignore'], + 'ignore: line before, star comment' => ['before' => '/* phpcs:ignore */'], + 'ignore: line before, star comment, with @' => ['before' => '/* @phpcs:ignore */'], + + // With suppression as trailing comment on code line. + 'ignore: end of line, slash comment' => [ + 'before' => '', + 'after' => ' // phpcs:ignore', + ], + 'ignore: end of line, slash comment, with @' => [ + 'before' => '', + 'after' => ' // @phpcs:ignore', + ], + 'ignore: end of line, hash comment' => [ + 'before' => '', + 'after' => ' # phpcs:ignore', + ], + 'ignore: end of line, hash comment, with @' => [ + 'before' => '', + 'after' => ' # @phpcs:ignore', + ], + + // Deprecated syntax. + 'old style: line before, slash comment' => ['before' => '// @codingStandardsIgnoreLine'], + 'old style: end of line, slash comment' => [ + 'before' => '', + 'after' => ' // @codingStandardsIgnoreLine', + ], + ]; + + }//end dataSuppressLine() + + + /** + * Test suppressing a single error using a single line ignore in the middle of a line. + * + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressLineMidLine() + { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.PHP.LowerCaseConstant']; + + $ruleset = new Ruleset($config); + + $content = 'process(); + + $this->assertSame(0, $file->getErrorCount()); + $this->assertCount(0, $file->getErrors()); + + }//end testSuppressLineMidLine() + + + /** + * Test suppressing a single error using a single line ignore within a docblock. + * + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressLineWithinDocblock() + { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.Files.LineLength']; + + $ruleset = new Ruleset($config); + + // Process with @ suppression on line before inside docblock. + $comment = str_repeat('a ', 50); + $content = <<process(); + + $this->assertSame(0, $file->getErrorCount()); + $this->assertCount(0, $file->getErrors()); + + }//end testSuppressLineWithinDocblock() + + + /** + * Test that using a single line ignore does not interfere with other suppressions. + * + * @param string $before Annotation to place before the code. + * @param string $after Annotation to place after the code. + * + * @dataProvider dataNestedSuppressLine + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testNestedSuppressLine($before, $after) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.PHP.LowerCaseConstant']; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame(0, $file->getErrorCount()); + $this->assertCount(0, $file->getErrors()); + + }//end testNestedSuppressLine() + + + /** + * Data provider. + * + * @see testNestedSuppressLine() + * + * @return array + */ + public function dataNestedSuppressLine() + { + return [ + // Process with disable/enable suppression and no single line suppression. + 'disable/enable: slash comment, no single line suppression' => [ + 'before' => '// phpcs:disable', + 'after' => '// phpcs:enable', + ], + 'disable/enable: slash comment, with @, no single line suppression' => [ + 'before' => '// @phpcs:disable', + 'after' => '// @phpcs:enable', + ], + 'disable/enable: hash comment, no single line suppression' => [ + 'before' => '# phpcs:disable', + 'after' => '# phpcs:enable', + ], + 'old style: slash comment, no single line suppression' => [ + 'before' => '// @codingStandardsIgnoreStart', + 'after' => '// @codingStandardsIgnoreEnd', + ], + + // Process with line suppression nested within disable/enable suppression. + 'disable/enable: slash comment, next line nested single line suppression' => [ + 'before' => '// phpcs:disable'.PHP_EOL.'// phpcs:ignore', + 'after' => '// phpcs:enable', + ], + 'disable/enable: slash comment, with @, next line nested single line suppression' => [ + 'before' => '// @phpcs:disable'.PHP_EOL.'// @phpcs:ignore', + 'after' => '// @phpcs:enable', + ], + 'disable/enable: hash comment, next line nested single line suppression' => [ + 'before' => '# @phpcs:disable'.PHP_EOL.'# @phpcs:ignore', + 'after' => '# @phpcs:enable', + ], + 'old style: slash comment, next line nested single line suppression' => [ + 'before' => '// @codingStandardsIgnoreStart'.PHP_EOL.'// @codingStandardsIgnoreLine', + 'after' => '// @codingStandardsIgnoreEnd', + ], + ]; + + }//end dataNestedSuppressLine() + + + /** + * Test suppressing a scope opener. + * + * @param string $before Annotation to place before the scope opener. + * @param string $after Annotation to place after the scope opener. + * @param int $expectedErrors Optional. Number of errors expected. + * Defaults to 0. + * + * @dataProvider dataSuppressScope + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressScope($before, $after, $expectedErrors=0) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['PEAR']; + $config->sniffs = ['PEAR.Functions.FunctionDeclaration']; + + $ruleset = new Ruleset($config); + } + + $content = 'foo(); + } +} +EOD; + $file = new DummyFile($content, $ruleset, $config); + $file->process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + }//end testSuppressScope() + + + /** + * Data provider. + * + * @see testSuppressScope() + * + * @return array + */ + public function dataSuppressScope() + { + return [ + 'no suppression' => [ + 'before' => '', + 'after' => '', + 'expectedErrors' => 1, + ], + + // Process with suppression. + 'disable/enable: slash comment' => [ + 'before' => '//phpcs:disable', + 'after' => '//phpcs:enable', + ], + 'disable/enable: slash comment, with @' => [ + 'before' => '//@phpcs:disable', + 'after' => '//@phpcs:enable', + ], + 'disable/enable: hash comment' => [ + 'before' => '#phpcs:disable', + 'after' => '#phpcs:enable', + ], + 'disable/enable: single line docblock comment' => [ + 'before' => '/** phpcs:disable */', + 'after' => '/** phpcs:enable */', + ], + 'disable/enable: single line docblock comment, with @' => [ + 'before' => '/** @phpcs:disable */', + 'after' => '/** @phpcs:enable */', + ], + + // Deprecated syntax. + 'old style: start/end, slash comment' => [ + 'before' => '//@codingStandardsIgnoreStart', + 'after' => '//@codingStandardsIgnoreEnd', + ], + 'old style: start/end, single line docblock comment' => [ + 'before' => '/** @codingStandardsIgnoreStart */', + 'after' => '/** @codingStandardsIgnoreEnd */', + ], + ]; + + }//end dataSuppressScope() + + + /** + * Test suppressing a whole file. + * + * @param string $before Annotation to place before the code. + * @param string $after Optional. Annotation to place after the code. + * Defaults to an empty string. + * @param int $expectedWarnings Optional. Number of warnings expected. + * Defaults to 0. + * + * @dataProvider dataSuppressFile + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testSuppressFile($before, $after='', $expectedWarnings=0) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = ['Generic.Commenting.Todo']; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testSuppressFile() + + + /** + * Data provider. + * + * @see testSuppressFile() + * + * @return array + */ + public function dataSuppressFile() + { + return [ + 'no suppression' => [ + 'before' => '', + 'after' => '', + 'expectedErrors' => 1, + ], + + // Process with suppression. + 'ignoreFile: start of file, slash comment' => ['before' => '// phpcs:ignoreFile'], + 'ignoreFile: start of file, slash comment, with @' => ['before' => '// @phpcs:ignoreFile'], + 'ignoreFile: start of file, slash comment, mixed case' => ['before' => '// PHPCS:Ignorefile'], + 'ignoreFile: start of file, hash comment' => ['before' => '# phpcs:ignoreFile'], + 'ignoreFile: start of file, hash comment, with @' => ['before' => '# @phpcs:ignoreFile'], + 'ignoreFile: start of file, single-line star comment' => ['before' => '/* phpcs:ignoreFile */'], + 'ignoreFile: start of file, multi-line star comment' => [ + 'before' => '/*'.PHP_EOL.' phpcs:ignoreFile'.PHP_EOL.' */', + ], + 'ignoreFile: start of file, single-line docblock comment' => ['before' => '/** phpcs:ignoreFile */'], + + // Process late comment. + 'ignoreFile: late comment, slash comment' => [ + 'before' => '', + 'after' => '// phpcs:ignoreFile', + ], + + // Deprecated syntax. + 'old style: start of file, slash comment' => ['before' => '// @codingStandardsIgnoreFile'], + 'old style: start of file, single-line star comment' => ['before' => '/* @codingStandardsIgnoreFile */'], + 'old style: start of file, multi-line star comment' => [ + 'before' => '/*'.PHP_EOL.' @codingStandardsIgnoreFile'.PHP_EOL.' */', + ], + 'old style: start of file, single-line docblock comment' => ['before' => '/** @codingStandardsIgnoreFile */'], + + // Deprecated syntax, late comment. + 'old style: late comment, slash comment' => [ + 'before' => '', + 'after' => '// @codingStandardsIgnoreFile', + ], + ]; + + }//end dataSuppressFile() + + + /** + * Test disabling specific sniffs. + * + * @param string $before Annotation to place before the code. + * @param int $expectedErrors Optional. Number of errors expected. + * Defaults to 0. + * @param int $expectedWarnings Optional. Number of warnings expected. + * Defaults to 0. + * + * @dataProvider dataDisableSelected + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testDisableSelected($before, $expectedErrors=0, $expectedWarnings=0) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = [ + 'Generic.PHP.LowerCaseConstant', + 'Generic.Commenting.Todo', + ]; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testDisableSelected() + + + /** + * Data provider. + * + * @see testDisableSelected() + * + * @return array + */ + public function dataDisableSelected() + { + return [ + // Single sniff. + 'disable: single sniff' => [ + 'before' => '// phpcs:disable Generic.Commenting.Todo', + 'expectedErrors' => 1, + ], + 'disable: single sniff with reason' => [ + 'before' => '# phpcs:disable Generic.Commenting.Todo -- for reasons', + 'expectedErrors' => 1, + ], + 'disable: single sniff, docblock' => [ + 'before' => '/**'.PHP_EOL.' * phpcs:disable Generic.Commenting.Todo'.PHP_EOL.' */ ', + 'expectedErrors' => 1, + ], + 'disable: single sniff, docblock, with @' => [ + 'before' => '/**'.PHP_EOL.' * @phpcs:disable Generic.Commenting.Todo'.PHP_EOL.' */ ', + 'expectedErrors' => 1, + ], + + // Multiple sniffs. + 'disable: multiple sniffs in one comment' => ['before' => '// phpcs:disable Generic.Commenting.Todo,Generic.PHP.LowerCaseConstant'], + 'disable: multiple sniff in multiple comments' => [ + 'before' => '// phpcs:disable Generic.Commenting.Todo'.PHP_EOL.'// phpcs:disable Generic.PHP.LowerCaseConstant', + ], + + // Selectiveness variations. + 'disable: complete category' => [ + 'before' => '// phpcs:disable Generic.Commenting', + 'expectedErrors' => 1, + ], + 'disable: whole standard' => ['before' => '// phpcs:disable Generic'], + 'disable: single errorcode' => [ + 'before' => '# @phpcs:disable Generic.Commenting.Todo.TaskFound', + 'expectedErrors' => 1, + ], + 'disable: single errorcode and a category' => ['before' => '// phpcs:disable Generic.PHP.LowerCaseConstant.Found,Generic.Commenting'], + + // Wrong category/sniff/code. + 'disable: wrong error code and category' => [ + 'before' => '/**'.PHP_EOL.' * phpcs:disable Generic.PHP.LowerCaseConstant.Upper,Generic.Comments'.PHP_EOL.' */ ', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: wrong category, docblock' => [ + 'before' => '/**'.PHP_EOL.' * phpcs:disable Generic.Files'.PHP_EOL.' */ ', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: wrong category, docblock, with @' => [ + 'before' => '/**'.PHP_EOL.' * @phpcs:disable Generic.Files'.PHP_EOL.' */ ', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + ]; + + }//end dataDisableSelected() + + + /** + * Test re-enabling specific sniffs that have been disabled. + * + * @param string $code Code pattern to check. + * @param int $expectedErrors Number of errors expected. + * @param int $expectedWarnings Number of warnings expected. + * + * @dataProvider dataEnableSelected + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testEnableSelected($code, $expectedErrors, $expectedWarnings) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = [ + 'Generic.PHP.LowerCaseConstant', + 'Generic.Commenting.Todo', + ]; + + $ruleset = new Ruleset($config); + } + + $content = 'process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testEnableSelected() + + + /** + * Data provider. + * + * @see testEnableSelected() + * + * @return array + */ + public function dataEnableSelected() + { + return [ + 'disable/enable: a single sniff' => [ + 'code' => ' + // phpcs:disable Generic.Commenting.Todo + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable/enable: multiple sniffs' => [ + 'code' => ' + // phpcs:disable Generic.Commenting.Todo,Generic.PHP.LowerCaseConstant + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo,Generic.PHP.LowerCaseConstant + //TODO: write some code + $var = FALSE;', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: multiple sniffs; enable: one' => [ + 'code' => ' + # phpcs:disable Generic.Commenting.Todo,Generic.PHP.LowerCaseConstant + $var = FALSE; + //TODO: write some code + # phpcs:enable Generic.Commenting.Todo + //TODO: write some code + $var = FALSE;', + 'expectedErrors' => 0, + 'expectedWarnings' => 1, + ], + 'disable/enable: complete category' => [ + 'code' => ' + // phpcs:disable Generic.Commenting + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable/enable: whole standard' => [ + 'code' => ' + // phpcs:disable Generic + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic + //TODO: write some code', + 'expectedErrors' => 0, + 'expectedWarnings' => 1, + ], + 'disable: whole standard; enable: category from the standard' => [ + 'code' => ' + // phpcs:disable Generic + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting + //TODO: write some code', + 'expectedErrors' => 0, + 'expectedWarnings' => 1, + ], + 'disable: a category; enable: the whole standard containing the category' => [ + 'code' => ' + # phpcs:disable Generic.Commenting + $var = FALSE; + //TODO: write some code + # phpcs:enable Generic + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: single sniff; enable: the category containing the sniff' => [ + 'code' => ' + // phpcs:disable Generic.Commenting.Todo + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: whole standard; enable: single sniff from the standard' => [ + 'code' => ' + // phpcs:disable Generic + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo + //TODO: write some code', + 'expectedErrors' => 0, + 'expectedWarnings' => 1, + ], + 'disable: whole standard; enable: single sniff from the standard; disable: that same sniff; enable: everything' => [ + 'code' => ' + // phpcs:disable Generic + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo + //TODO: write some code + // phpcs:disable Generic.Commenting.Todo + //TODO: write some code + // phpcs:enable + //TODO: write some code', + 'expectedErrors' => 0, + 'expectedWarnings' => 2, + ], + 'disable: whole standard; enable: single sniff from the standard; enable: other sniff from the standard' => [ + 'code' => ' + // phpcs:disable Generic + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo + //TODO: write some code + $var = FALSE; + // phpcs:enable Generic.PHP.LowerCaseConstant + //TODO: write some code + $var = FALSE;', + 'expectedErrors' => 1, + 'expectedWarnings' => 2, + ], + ]; + + }//end dataEnableSelected() + + + /** + * Test ignoring specific sniffs. + * + * @param string $before Annotation to place before the code. + * @param int $expectedErrors Number of errors expected. + * @param int $expectedWarnings Number of warnings expected. + * + * @dataProvider dataIgnoreSelected + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testIgnoreSelected($before, $expectedErrors, $expectedWarnings) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = [ + 'Generic.PHP.LowerCaseConstant', + 'Generic.Commenting.Todo', + ]; + + $ruleset = new Ruleset($config); + } + + $content = <<process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testIgnoreSelected() + + + /** + * Data provider. + * + * @see testIgnoreSelected() + * + * @return array + */ + public function dataIgnoreSelected() + { + return [ + 'no suppression' => [ + 'before' => '', + 'expectedErrors' => 2, + 'expectedWarnings' => 2, + ], + + // With suppression. + 'ignore: single sniff' => [ + 'before' => '// phpcs:ignore Generic.Commenting.Todo', + 'expectedErrors' => 2, + 'expectedWarnings' => 1, + ], + 'ignore: multiple sniffs' => [ + 'before' => '// phpcs:ignore Generic.Commenting.Todo,Generic.PHP.LowerCaseConstant', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: single sniff; ignore: single sniff' => [ + 'before' => '// phpcs:disable Generic.Commenting.Todo'.PHP_EOL.'// phpcs:ignore Generic.PHP.LowerCaseConstant', + 'expectedErrors' => 1, + 'expectedWarnings' => 0, + ], + 'ignore: category of sniffs' => [ + 'before' => '# phpcs:ignore Generic.Commenting', + 'expectedErrors' => 2, + 'expectedWarnings' => 1, + ], + 'ignore: whole standard' => [ + 'before' => '// phpcs:ignore Generic', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + ]; + + }//end dataIgnoreSelected() + + + /** + * Test ignoring specific sniffs. + * + * @param string $code Code pattern to check. + * @param int $expectedErrors Number of errors expected. + * @param int $expectedWarnings Number of warnings expected. + * + * @dataProvider dataCommenting + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testCommenting($code, $expectedErrors, $expectedWarnings) + { + static $config, $ruleset; + + if (isset($config, $ruleset) === false) { + $config = new Config(); + $config->standards = ['Generic']; + $config->sniffs = [ + 'Generic.PHP.LowerCaseConstant', + 'Generic.Commenting.Todo', + ]; + + $ruleset = new Ruleset($config); + } + + $content = 'process(); + + $this->assertSame($expectedErrors, $file->getErrorCount()); + $this->assertCount($expectedErrors, $file->getErrors()); + + $this->assertSame($expectedWarnings, $file->getWarningCount()); + $this->assertCount($expectedWarnings, $file->getWarnings()); + + }//end testCommenting() + + + /** + * Data provider. + * + * @see testCommenting() + * + * @return array + */ + public function dataCommenting() + { + return [ + 'ignore: single sniff' => [ + 'code' => ' + // phpcs:ignore Generic.Commenting.Todo -- Because reasons + $var = FALSE; //TODO: write some code + $var = FALSE; //TODO: write some code', + 'expectedErrors' => 2, + 'expectedWarnings' => 1, + ], + 'disable: single sniff; enable: same sniff - test whitespace handling around reason delimiter' => [ + 'code' => ' + // phpcs:disable Generic.Commenting.Todo --Because reasons + $var = FALSE; + //TODO: write some code + // phpcs:enable Generic.Commenting.Todo -- Because reasons + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 1, + ], + 'disable: single sniff, multi-line comment' => [ + 'code' => ' + /* + Disable some checks + phpcs:disable Generic.Commenting.Todo + */ + $var = FALSE; + //TODO: write some code', + 'expectedErrors' => 1, + 'expectedWarnings' => 0, + ], + 'ignore: single sniff, multi-line slash comment' => [ + 'code' => ' + // Turn off a check for the next line of code. + // phpcs:ignore Generic.Commenting.Todo + $var = FALSE; //TODO: write some code + $var = FALSE; //TODO: write some code', + 'expectedErrors' => 2, + 'expectedWarnings' => 1, + ], + 'enable before disable, sniff not in standard' => [ + 'code' => ' + // phpcs:enable Generic.PHP.NoSilencedErrors -- Because reasons + $var = @delete( $filename ); + ', + 'expectedErrors' => 0, + 'expectedWarnings' => 0, + ], + ]; + + }//end dataCommenting() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.inc new file mode 100644 index 0000000..8351679 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.inc @@ -0,0 +1,105 @@ + fn() => return 1, + 'b' => fn() => return 1, +]; + +/* testStaticArrowFunction */ +static fn ($a) => $a; + +return 0; + +/* testArrowFunctionReturnValue */ +fn(): array => [a($a, $b)]; + +/* testArrowFunctionAsArgument */ +$foo = foo( + fn() => bar() +); + +/* testArrowFunctionWithArrayAsArgument */ +$foo = foo( + fn() => [$row[0], $row[3]] +); + +$match = match ($a) { + /* testMatchCase */ + 1 => 'foo', + /* testMatchDefault */ + default => 'bar' +}; + +$match = match ($a) { + /* testMatchMultipleCase */ + 1, 2, => $a * $b, + /* testMatchDefaultComma */ + default, => 'something' +}; + +match ($pressedKey) { + /* testMatchFunctionCall */ + Key::RETURN_ => save($value, $user) +}; + +$result = match (true) { + /* testMatchFunctionCallArm */ + str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en', + str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr', + default => 'pl' +}; + +/* testMatchClosure */ +$result = match ($key) { + 1 => function($a, $b) {}, + 2 => function($b, $c) {}, +}; + +/* testMatchArray */ +$result = match ($key) { + 1 => [1,2,3], + 2 => [1 => one(), 2 => two()], +}; + +/* testNestedMatch */ +$result = match ($key) { + 1 => match ($key) { + 1 => 'one', + 2 => 'two', + }, + 2 => match ($key) { + 1 => 'two', + 2 => 'one', + }, +}; diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.php new file mode 100644 index 0000000..6296db6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindEndOfStatementTest.php @@ -0,0 +1,420 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::findEndOfStatement method. + * + * @covers \PHP_CodeSniffer\Files\File::findEndOfStatement + */ +class FindEndOfStatementTest extends AbstractMethodUnitTest +{ + + + /** + * Test a simple assignment. + * + * @return void + */ + public function testSimpleAssignment() + { + $start = $this->getTargetToken('/* testSimpleAssignment */', T_VARIABLE); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 5), $found); + + }//end testSimpleAssignment() + + + /** + * Test a direct call to a control structure. + * + * @return void + */ + public function testControlStructure() + { + $start = $this->getTargetToken('/* testControlStructure */', T_WHILE); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 6), $found); + + }//end testControlStructure() + + + /** + * Test the assignment of a closure. + * + * @return void + */ + public function testClosureAssignment() + { + $start = $this->getTargetToken('/* testClosureAssignment */', T_VARIABLE, '$a'); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 13), $found); + + }//end testClosureAssignment() + + + /** + * Test using a heredoc in a function argument. + * + * @return void + */ + public function testHeredocFunctionArg() + { + // Find the end of the function. + $start = $this->getTargetToken('/* testHeredocFunctionArg */', T_STRING, 'myFunction'); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 10), $found); + + // Find the end of the heredoc. + $start += 2; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 4), $found); + + // Find the end of the last arg. + $start = ($found + 2); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame($start, $found); + + }//end testHeredocFunctionArg() + + + /** + * Test parts of a switch statement. + * + * @return void + */ + public function testSwitch() + { + // Find the end of the switch. + $start = $this->getTargetToken('/* testSwitch */', T_SWITCH); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 28), $found); + + // Find the end of the case. + $start += 9; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 8), $found); + + // Find the end of default case. + $start += 11; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 6), $found); + + }//end testSwitch() + + + /** + * Test statements that are array values. + * + * @return void + */ + public function testStatementAsArrayValue() + { + // Test short array syntax. + $start = $this->getTargetToken('/* testStatementAsArrayValue */', T_NEW); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 2), $found); + + // Test long array syntax. + $start += 12; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 2), $found); + + // Test same statement outside of array. + $start += 10; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 3), $found); + + }//end testStatementAsArrayValue() + + + /** + * Test a use group. + * + * @return void + */ + public function testUseGroup() + { + $start = $this->getTargetToken('/* testUseGroup */', T_USE); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 23), $found); + + }//end testUseGroup() + + + /** + * Test arrow function as array value. + * + * @return void + */ + public function testArrowFunctionArrayValue() + { + $start = $this->getTargetToken('/* testArrowFunctionArrayValue */', T_FN); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 9), $found); + + }//end testArrowFunctionArrayValue() + + + /** + * Test static arrow function. + * + * @return void + */ + public function testStaticArrowFunction() + { + $static = $this->getTargetToken('/* testStaticArrowFunction */', T_STATIC); + $fn = $this->getTargetToken('/* testStaticArrowFunction */', T_FN); + + $endOfStatementStatic = self::$phpcsFile->findEndOfStatement($static); + $endOfStatementFn = self::$phpcsFile->findEndOfStatement($fn); + + $this->assertSame($endOfStatementFn, $endOfStatementStatic); + + }//end testStaticArrowFunction() + + + /** + * Test arrow function with return value. + * + * @return void + */ + public function testArrowFunctionReturnValue() + { + $start = $this->getTargetToken('/* testArrowFunctionReturnValue */', T_FN); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 18), $found); + + }//end testArrowFunctionReturnValue() + + + /** + * Test arrow function used as a function argument. + * + * @return void + */ + public function testArrowFunctionAsArgument() + { + $start = $this->getTargetToken('/* testArrowFunctionAsArgument */', T_FN); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 8), $found); + + }//end testArrowFunctionAsArgument() + + + /** + * Test arrow function with arrays used as a function argument. + * + * @return void + */ + public function testArrowFunctionWithArrayAsArgument() + { + $start = $this->getTargetToken('/* testArrowFunctionWithArrayAsArgument */', T_FN); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 17), $found); + + }//end testArrowFunctionWithArrayAsArgument() + + + /** + * Test simple match expression case. + * + * @return void + */ + public function testMatchCase() + { + $start = $this->getTargetToken('/* testMatchCase */', T_LNUMBER); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 5), $found); + + $start = $this->getTargetToken('/* testMatchCase */', T_CONSTANT_ENCAPSED_STRING); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 1), $found); + + }//end testMatchCase() + + + /** + * Test simple match expression default case. + * + * @return void + */ + public function testMatchDefault() + { + $start = $this->getTargetToken('/* testMatchDefault */', T_MATCH_DEFAULT); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 4), $found); + + $start = $this->getTargetToken('/* testMatchDefault */', T_CONSTANT_ENCAPSED_STRING); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame($start, $found); + + }//end testMatchDefault() + + + /** + * Test multiple comma-separated match expression case values. + * + * @return void + */ + public function testMatchMultipleCase() + { + $start = $this->getTargetToken('/* testMatchMultipleCase */', T_LNUMBER); + $found = self::$phpcsFile->findEndOfStatement($start); + $this->assertSame(($start + 13), $found); + + $start += 6; + $found = self::$phpcsFile->findEndOfStatement($start); + $this->assertSame(($start + 7), $found); + + }//end testMatchMultipleCase() + + + /** + * Test match expression default case with trailing comma. + * + * @return void + */ + public function testMatchDefaultComma() + { + $start = $this->getTargetToken('/* testMatchDefaultComma */', T_MATCH_DEFAULT); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 5), $found); + + }//end testMatchDefaultComma() + + + /** + * Test match expression with function call. + * + * @return void + */ + public function testMatchFunctionCall() + { + $start = $this->getTargetToken('/* testMatchFunctionCall */', T_STRING); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 12), $found); + + $start += 8; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 1), $found); + + }//end testMatchFunctionCall() + + + /** + * Test match expression with function call in the arm. + * + * @return void + */ + public function testMatchFunctionCallArm() + { + // Check the first case. + $start = $this->getTargetToken('/* testMatchFunctionCallArm */', T_STRING); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 21), $found); + + // Check the second case. + $start += 24; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 21), $found); + + }//end testMatchFunctionCallArm() + + + /** + * Test match expression with closure. + * + * @return void + */ + public function testMatchClosure() + { + $start = $this->getTargetToken('/* testMatchClosure */', T_LNUMBER); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 14), $found); + + $start += 17; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 14), $found); + + }//end testMatchClosure() + + + /** + * Test match expression with array declaration. + * + * @return void + */ + public function testMatchArray() + { + $start = $this->getTargetToken('/* testMatchArray */', T_LNUMBER); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 11), $found); + + $start += 14; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 22), $found); + + }//end testMatchArray() + + + /** + * Test nested match expressions. + * + * @return void + */ + public function testNestedMatch() + { + $start = $this->getTargetToken('/* testNestedMatch */', T_LNUMBER); + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 30), $found); + + $start += 21; + $found = self::$phpcsFile->findEndOfStatement($start); + + $this->assertSame(($start + 5), $found); + + }//end testNestedMatch() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindExtendedClassNameTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindExtendedClassNameTest.inc new file mode 100644 index 0000000..dae2cd9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindExtendedClassNameTest.inc @@ -0,0 +1,52 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::findExtendedClassName method. + * + * @covers \PHP_CodeSniffer\Files\File::findExtendedClassName + */ +class FindExtendedClassNameTest extends AbstractMethodUnitTest +{ + + + /** + * Test getting a `false` result when a non-existent token is passed. + * + * @return void + */ + public function testNonExistentToken() + { + $result = self::$phpcsFile->findExtendedClassName(100000); + $this->assertFalse($result); + + }//end testNonExistentToken() + + + /** + * Test getting a `false` result when a token other than one of the supported tokens is passed. + * + * @return void + */ + public function testNotAClass() + { + $token = $this->getTargetToken('/* testNotAClass */', [T_FUNCTION]); + $result = self::$phpcsFile->findExtendedClassName($token); + $this->assertFalse($result); + + }//end testNotAClass() + + + /** + * Test retrieving the name of the class being extended by another class + * (or interface). + * + * @param string $identifier Comment which precedes the test case. + * @param string|false $expected Expected function output. + * + * @dataProvider dataExtendedClass + * + * @return void + */ + public function testFindExtendedClassName($identifier, $expected) + { + $OOToken = $this->getTargetToken($identifier, [T_CLASS, T_ANON_CLASS, T_INTERFACE]); + $result = self::$phpcsFile->findExtendedClassName($OOToken); + $this->assertSame($expected, $result); + + }//end testFindExtendedClassName() + + + /** + * Data provider for the FindExtendedClassName test. + * + * @see testFindExtendedClassName() + * + * @return array> + */ + public function dataExtendedClass() + { + return [ + 'class does not extend' => [ + 'identifier' => '/* testNonExtendedClass */', + 'expected' => false, + ], + 'class extends unqualified class' => [ + 'identifier' => '/* testExtendsUnqualifiedClass */', + 'expected' => 'testFECNClass', + ], + 'class extends fully qualified class' => [ + 'identifier' => '/* testExtendsFullyQualifiedClass */', + 'expected' => '\PHP_CodeSniffer\Tests\Core\File\testFECNClass', + ], + 'class extends partially qualified class' => [ + 'identifier' => '/* testExtendsPartiallyQualifiedClass */', + 'expected' => 'Core\File\RelativeClass', + ], + 'interface does not extend' => [ + 'identifier' => '/* testNonExtendedInterface */', + 'expected' => false, + ], + 'interface extends unqualified interface' => [ + 'identifier' => '/* testInterfaceExtendsUnqualifiedInterface */', + 'expected' => 'testFECNInterface', + ], + 'interface extends fully qualified interface' => [ + 'identifier' => '/* testInterfaceExtendsFullyQualifiedInterface */', + 'expected' => '\PHP_CodeSniffer\Tests\Core\File\testFECNInterface', + ], + 'anon class extends unqualified class' => [ + 'identifier' => '/* testExtendedAnonClass */', + 'expected' => 'testFECNExtendedAnonClass', + ], + 'class does not extend but contains anon class which extends' => [ + 'identifier' => '/* testNestedExtendedClass */', + 'expected' => false, + ], + 'anon class extends, nested in non-extended class' => [ + 'identifier' => '/* testNestedExtendedAnonClass */', + 'expected' => 'testFECNAnonClass', + ], + 'class extends and implements' => [ + 'identifier' => '/* testClassThatExtendsAndImplements */', + 'expected' => 'testFECNClass', + ], + 'class implements and extends' => [ + 'identifier' => '/* testClassThatImplementsAndExtends */', + 'expected' => 'testFECNClass', + ], + 'interface extends multiple interfaces (not supported)' => [ + 'identifier' => '/* testInterfaceMultiExtends */', + 'expected' => '\Package\FooInterface', + ], + 'parse error - extends keyword, but no class name' => [ + 'identifier' => '/* testMissingExtendsName */', + 'expected' => false, + ], + 'parse error - live coding - no curly braces' => [ + 'identifier' => '/* testParseError */', + 'expected' => false, + ], + ]; + + }//end dataExtendedClass() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindImplementedInterfaceNamesTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindImplementedInterfaceNamesTest.inc new file mode 100644 index 0000000..3246efa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindImplementedInterfaceNamesTest.inc @@ -0,0 +1,47 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::findImplementedInterfaceNames method. + * + * @covers \PHP_CodeSniffer\Files\File::findImplementedInterfaceNames + */ +class FindImplementedInterfaceNamesTest extends AbstractMethodUnitTest +{ + + + /** + * Test getting a `false` result when a non-existent token is passed. + * + * @return void + */ + public function testNonExistentToken() + { + $result = self::$phpcsFile->findImplementedInterfaceNames(100000); + $this->assertFalse($result); + + }//end testNonExistentToken() + + + /** + * Test getting a `false` result when a token other than one of the supported tokens is passed. + * + * @return void + */ + public function testNotAClass() + { + $token = $this->getTargetToken('/* testNotAClass */', [T_FUNCTION]); + $result = self::$phpcsFile->findImplementedInterfaceNames($token); + $this->assertFalse($result); + + }//end testNotAClass() + + + /** + * Test retrieving the name(s) of the interfaces being implemented by a class. + * + * @param string $identifier Comment which precedes the test case. + * @param array|false $expected Expected function output. + * + * @dataProvider dataImplementedInterface + * + * @return void + */ + public function testFindImplementedInterfaceNames($identifier, $expected) + { + $OOToken = $this->getTargetToken($identifier, [T_CLASS, T_ANON_CLASS, T_INTERFACE, T_ENUM]); + $result = self::$phpcsFile->findImplementedInterfaceNames($OOToken); + $this->assertSame($expected, $result); + + }//end testFindImplementedInterfaceNames() + + + /** + * Data provider for the FindImplementedInterfaceNames test. + * + * @see testFindImplementedInterfaceNames() + * + * @return array>> + */ + public function dataImplementedInterface() + { + return [ + 'interface declaration, no implements' => [ + 'identifier' => '/* testPlainInterface */', + 'expected' => false, + ], + 'class does not implement' => [ + 'identifier' => '/* testNonImplementedClass */', + 'expected' => false, + ], + 'class implements single interface, unqualified' => [ + 'identifier' => '/* testClassImplementsSingle */', + 'expected' => ['testFIINInterface'], + ], + 'class implements multiple interfaces' => [ + 'identifier' => '/* testClassImplementsMultiple */', + 'expected' => [ + 'testFIINInterface', + 'testFIINInterface2', + ], + ], + 'class implements single interface, fully qualified' => [ + 'identifier' => '/* testImplementsFullyQualified */', + 'expected' => ['\PHP_CodeSniffer\Tests\Core\File\testFIINInterface'], + ], + 'class implements single interface, partially qualified' => [ + 'identifier' => '/* testImplementsPartiallyQualified */', + 'expected' => ['Core\File\RelativeInterface'], + ], + 'class extends and implements' => [ + 'identifier' => '/* testClassThatExtendsAndImplements */', + 'expected' => [ + 'InterfaceA', + '\NameSpaced\Cat\InterfaceB', + ], + ], + 'class implements and extends' => [ + 'identifier' => '/* testClassThatImplementsAndExtends */', + 'expected' => [ + '\InterfaceA', + 'InterfaceB', + ], + ], + 'enum does not implement' => [ + 'identifier' => '/* testBackedEnumWithoutImplements */', + 'expected' => false, + ], + 'enum implements single interface, unqualified' => [ + 'identifier' => '/* testEnumImplementsSingle */', + 'expected' => ['Colorful'], + ], + 'enum implements multiple interfaces, unqualified + fully qualified' => [ + 'identifier' => '/* testBackedEnumImplementsMulti */', + 'expected' => [ + 'Colorful', + '\Deck', + ], + ], + 'anon class implements single interface, unqualified' => [ + 'identifier' => '/* testAnonClassImplementsSingle */', + 'expected' => ['testFIINInterface'], + ], + 'parse error - implements keyword, but no interface name' => [ + 'identifier' => '/* testMissingImplementsName */', + 'expected' => false, + ], + 'parse error - live coding - no curly braces' => [ + 'identifier' => '/* testParseError */', + 'expected' => false, + ], + ]; + + }//end dataImplementedInterface() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.inc new file mode 100644 index 0000000..148d810 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.inc @@ -0,0 +1,164 @@ + $foo + $bar, 'b' => true]; + +/* testUseGroup */ +use Vendor\Package\{ClassA as A, ClassB, ClassC as C}; + +$a = [ + /* testArrowFunctionArrayValue */ + 'a' => fn() => return 1, + 'b' => fn() => return 1, +]; + +/* testStaticArrowFunction */ +static fn ($a) => $a; + +/* testArrowFunctionReturnValue */ +fn(): array => [a($a, $b)]; + +/* testArrowFunctionAsArgument */ +$foo = foo( + fn() => bar() +); + +/* testArrowFunctionWithArrayAsArgument */ +$foo = foo( + fn() => [$row[0], $row[3]] +); + +$match = match ($a) { + /* testMatchCase */ + 1 => 'foo', + /* testMatchDefault */ + default => 'bar' +}; + +$match = match ($a) { + /* testMatchMultipleCase */ + 1, 2, => $a * $b, + /* testMatchDefaultComma */ + default, => 'something' +}; + +match ($pressedKey) { + /* testMatchFunctionCall */ + Key::RETURN_ => save($value, $user) +}; + +$result = match (true) { + /* testMatchFunctionCallArm */ + str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en', + str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr', + default => 'pl' +}; + +/* testMatchClosure */ +$result = match ($key) { + 1 => function($a, $b) {}, + 2 => function($b, $c) {}, +}; + +/* testMatchArray */ +$result = match ($key) { + 1 => [1,2,3], + 2 => [1 => one($a, $b), 2 => two($b, $c)], + 3 => [], +}; + +/* testNestedMatch */ +$result = match ($key) { + 1 => match ($key) { + 1 => 'one', + 2 => 'two', + }, + 2 => match ($key) { + 1 => 'two', + 2 => 'one', + }, +}; + +return 0; + +/* testOpenTag */ +?> +

    Test

    +', foo(), ''; + +/* testOpenTagWithEcho */ +?> +

    Test

    +', foo(), ''; + +$value = [ + /* testPrecededByArrowFunctionInArray - Expected */ + Url::make('View Song', fn($song) => $song->url()) + /* testPrecededByArrowFunctionInArray */ + ->onlyOnDetail(), + + new Panel('Information', [ + Text::make('Title') + ]), +]; + +switch ($foo) { + /* testCaseStatement */ + case 1: + /* testInsideCaseStatement */ + $var = doSomething(); + /* testInsideCaseBreakStatement */ + break 2; + + case 2: + /* testInsideCaseContinueStatement */ + continue 2; + + case 3: + /* testInsideCaseReturnStatement */ + return false; + + case 4: + /* testInsideCaseExitStatement */ + exit(1); + + case 5: + /* testInsideCaseThrowStatement */ + throw new Exception(); + + /* testDefaultStatement */ + default: + /* testInsideDefaultContinueStatement */ + continue $var; +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.php new file mode 100644 index 0000000..334d05b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/FindStartOfStatementTest.php @@ -0,0 +1,640 @@ + + * @author Juliette Reinders Folmer + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @copyright 2019-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:findStartOfStatement method. + * + * @covers \PHP_CodeSniffer\Files\File::findStartOfStatement + */ +class FindStartOfStatementTest extends AbstractMethodUnitTest +{ + + + /** + * Test a simple assignment. + * + * @return void + */ + public function testSimpleAssignment() + { + $start = $this->getTargetToken('/* testSimpleAssignment */', T_SEMICOLON); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 5), $found); + + }//end testSimpleAssignment() + + + /** + * Test a function call. + * + * @return void + */ + public function testFunctionCall() + { + $start = $this->getTargetToken('/* testFunctionCall */', T_CLOSE_PARENTHESIS); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 6), $found); + + }//end testFunctionCall() + + + /** + * Test a function call. + * + * @return void + */ + public function testFunctionCallArgument() + { + $start = $this->getTargetToken('/* testFunctionCallArgument */', T_VARIABLE, '$b'); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame($start, $found); + + }//end testFunctionCallArgument() + + + /** + * Test a direct call to a control structure. + * + * @return void + */ + public function testControlStructure() + { + $start = $this->getTargetToken('/* testControlStructure */', T_CLOSE_CURLY_BRACKET); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 6), $found); + + }//end testControlStructure() + + + /** + * Test the assignment of a closure. + * + * @return void + */ + public function testClosureAssignment() + { + $start = $this->getTargetToken('/* testClosureAssignment */', T_CLOSE_CURLY_BRACKET); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 12), $found); + + }//end testClosureAssignment() + + + /** + * Test using a heredoc in a function argument. + * + * @return void + */ + public function testHeredocFunctionArg() + { + // Find the start of the function. + $start = $this->getTargetToken('/* testHeredocFunctionArg */', T_SEMICOLON); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 10), $found); + + // Find the start of the heredoc. + $start -= 4; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 4), $found); + + // Find the start of the last arg. + $start += 2; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame($start, $found); + + }//end testHeredocFunctionArg() + + + /** + * Test parts of a switch statement. + * + * @return void + */ + public function testSwitch() + { + // Find the start of the switch. + $start = $this->getTargetToken('/* testSwitch */', T_CLOSE_CURLY_BRACKET); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 47), $found); + + // Find the start of default case. + $start -= 5; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 6), $found); + + // Find the start of the second case. + $start -= 12; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 5), $found); + + // Find the start of the first case. + $start -= 13; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 8), $found); + + // Test inside the first case. + $start--; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 1), $found); + + }//end testSwitch() + + + /** + * Test statements that are array values. + * + * @return void + */ + public function testStatementAsArrayValue() + { + // Test short array syntax. + $start = $this->getTargetToken('/* testStatementAsArrayValue */', T_STRING, 'Datetime'); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 2), $found); + + // Test long array syntax. + $start += 12; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 2), $found); + + // Test same statement outside of array. + $start++; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 9), $found); + + // Test with an array index. + $start += 17; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 5), $found); + + }//end testStatementAsArrayValue() + + + /** + * Test a use group. + * + * @return void + */ + public function testUseGroup() + { + $start = $this->getTargetToken('/* testUseGroup */', T_SEMICOLON); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 23), $found); + + }//end testUseGroup() + + + /** + * Test arrow function as array value. + * + * @return void + */ + public function testArrowFunctionArrayValue() + { + $start = $this->getTargetToken('/* testArrowFunctionArrayValue */', T_COMMA); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 9), $found); + + }//end testArrowFunctionArrayValue() + + + /** + * Test static arrow function. + * + * @return void + */ + public function testStaticArrowFunction() + { + $start = $this->getTargetToken('/* testStaticArrowFunction */', T_SEMICOLON); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 11), $found); + + }//end testStaticArrowFunction() + + + /** + * Test arrow function with return value. + * + * @return void + */ + public function testArrowFunctionReturnValue() + { + $start = $this->getTargetToken('/* testArrowFunctionReturnValue */', T_SEMICOLON); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 18), $found); + + }//end testArrowFunctionReturnValue() + + + /** + * Test arrow function used as a function argument. + * + * @return void + */ + public function testArrowFunctionAsArgument() + { + $start = $this->getTargetToken('/* testArrowFunctionAsArgument */', T_FN); + $start += 8; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 8), $found); + + }//end testArrowFunctionAsArgument() + + + /** + * Test arrow function with arrays used as a function argument. + * + * @return void + */ + public function testArrowFunctionWithArrayAsArgument() + { + $start = $this->getTargetToken('/* testArrowFunctionWithArrayAsArgument */', T_FN); + $start += 17; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 17), $found); + + }//end testArrowFunctionWithArrayAsArgument() + + + /** + * Test simple match expression case. + * + * @return void + */ + public function testMatchCase() + { + $start = $this->getTargetToken('/* testMatchCase */', T_COMMA); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 1), $found); + + }//end testMatchCase() + + + /** + * Test simple match expression default case. + * + * @return void + */ + public function testMatchDefault() + { + $start = $this->getTargetToken('/* testMatchDefault */', T_CONSTANT_ENCAPSED_STRING, "'bar'"); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame($start, $found); + + }//end testMatchDefault() + + + /** + * Test multiple comma-separated match expression case values. + * + * @return void + */ + public function testMatchMultipleCase() + { + $start = $this->getTargetToken('/* testMatchMultipleCase */', T_MATCH_ARROW); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 6), $found); + + $start += 6; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 4), $found); + + }//end testMatchMultipleCase() + + + /** + * Test match expression default case with trailing comma. + * + * @return void + */ + public function testMatchDefaultComma() + { + $start = $this->getTargetToken('/* testMatchDefaultComma */', T_MATCH_ARROW); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 3), $found); + + $start += 2; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame($start, $found); + + }//end testMatchDefaultComma() + + + /** + * Test match expression with function call. + * + * @return void + */ + public function testMatchFunctionCall() + { + $start = $this->getTargetToken('/* testMatchFunctionCall */', T_CLOSE_PARENTHESIS); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 6), $found); + + }//end testMatchFunctionCall() + + + /** + * Test match expression with function call in the arm. + * + * @return void + */ + public function testMatchFunctionCallArm() + { + // Check the first case. + $start = $this->getTargetToken('/* testMatchFunctionCallArm */', T_MATCH_ARROW); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 18), $found); + + // Check the second case. + $start += 24; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 18), $found); + + }//end testMatchFunctionCallArm() + + + /** + * Test match expression with closure. + * + * @return void + */ + public function testMatchClosure() + { + $start = $this->getTargetToken('/* testMatchClosure */', T_LNUMBER); + $start += 14; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 10), $found); + + $start += 17; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 10), $found); + + }//end testMatchClosure() + + + /** + * Test match expression with array declaration. + * + * @return void + */ + public function testMatchArray() + { + // Start of first case statement. + $start = $this->getTargetToken('/* testMatchArray */', T_LNUMBER); + $found = self::$phpcsFile->findStartOfStatement($start); + $this->assertSame($start, $found); + + // Comma after first statement. + $start += 11; + $found = self::$phpcsFile->findStartOfStatement($start); + $this->assertSame(($start - 7), $found); + + // Start of second case statement. + $start += 3; + $found = self::$phpcsFile->findStartOfStatement($start); + $this->assertSame($start, $found); + + // Comma after first statement. + $start += 30; + $found = self::$phpcsFile->findStartOfStatement($start); + $this->assertSame(($start - 26), $found); + + }//end testMatchArray() + + + /** + * Test nested match expressions. + * + * @return void + */ + public function testNestedMatch() + { + $start = $this->getTargetToken('/* testNestedMatch */', T_LNUMBER); + $start += 30; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 26), $found); + + $start -= 4; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 1), $found); + + $start -= 3; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 2), $found); + + }//end testNestedMatch() + + + /** + * Test PHP open tag. + * + * @return void + */ + public function testOpenTag() + { + $start = $this->getTargetToken('/* testOpenTag */', T_OPEN_TAG); + $start += 2; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 1), $found); + + }//end testOpenTag() + + + /** + * Test PHP short open echo tag. + * + * @return void + */ + public function testOpenTagWithEcho() + { + $start = $this->getTargetToken('/* testOpenTagWithEcho */', T_OPEN_TAG_WITH_ECHO); + $start += 3; + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame(($start - 1), $found); + + }//end testOpenTagWithEcho() + + + /** + * Test object call on result of static function call with arrow function as parameter and wrapped within an array. + * + * @link https://github.com/squizlabs/PHP_CodeSniffer/issues/2849 + * @link https://github.com/squizlabs/PHP_CodeSniffer/commit/fbf67efc3fc0c2a355f5585d49f4f6fe160ff2f9 + * + * @return void + */ + public function testObjectCallPrecededByArrowFunctionAsFunctionCallParameterInArray() + { + $expected = $this->getTargetToken('/* testPrecededByArrowFunctionInArray - Expected */', T_STRING, 'Url'); + + $start = $this->getTargetToken('/* testPrecededByArrowFunctionInArray */', T_STRING, 'onlyOnDetail'); + $found = self::$phpcsFile->findStartOfStatement($start); + + $this->assertSame($expected, $found); + + }//end testObjectCallPrecededByArrowFunctionAsFunctionCallParameterInArray() + + + /** + * Test finding the start of a statement inside a switch control structure case/default statement. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $targets The token to search for after the test marker. + * @param string|int $expectedTarget Token code of the expected start of statement stack pointer. + * + * @link https://github.com/squizlabs/php_codesniffer/issues/3192 + * @link https://github.com/squizlabs/PHP_CodeSniffer/pull/3186/commits/18a0e54735bb9b3850fec266e5f4c50dacf618ea + * + * @dataProvider dataFindStartInsideSwitchCaseDefaultStatements + * + * @return void + */ + public function testFindStartInsideSwitchCaseDefaultStatements($testMarker, $targets, $expectedTarget) + { + $testToken = $this->getTargetToken($testMarker, $targets); + $expected = $this->getTargetToken($testMarker, $expectedTarget); + + $found = self::$phpcsFile->findStartOfStatement($testToken); + + $this->assertSame($expected, $found); + + }//end testFindStartInsideSwitchCaseDefaultStatements() + + + /** + * Data provider. + * + * @return array> + */ + public static function dataFindStartInsideSwitchCaseDefaultStatements() + { + return [ + 'Case keyword should be start of case statement - case itself' => [ + 'testMarker' => '/* testCaseStatement */', + 'targets' => T_CASE, + 'expectedTarget' => T_CASE, + ], + 'Case keyword should be start of case statement - number (what\'s being compared)' => [ + 'testMarker' => '/* testCaseStatement */', + 'targets' => T_LNUMBER, + 'expectedTarget' => T_CASE, + ], + 'Variable should be start of arbitrary assignment statement - variable itself' => [ + 'testMarker' => '/* testInsideCaseStatement */', + 'targets' => T_VARIABLE, + 'expectedTarget' => T_VARIABLE, + ], + 'Variable should be start of arbitrary assignment statement - equal sign' => [ + 'testMarker' => '/* testInsideCaseStatement */', + 'targets' => T_EQUAL, + 'expectedTarget' => T_VARIABLE, + ], + 'Variable should be start of arbitrary assignment statement - function call' => [ + 'testMarker' => '/* testInsideCaseStatement */', + 'targets' => T_STRING, + 'expectedTarget' => T_VARIABLE, + ], + 'Break should be start for contents of the break statement - contents' => [ + 'testMarker' => '/* testInsideCaseBreakStatement */', + 'targets' => T_LNUMBER, + 'expectedTarget' => T_BREAK, + ], + 'Continue should be start for contents of the continue statement - contents' => [ + 'testMarker' => '/* testInsideCaseContinueStatement */', + 'targets' => T_LNUMBER, + 'expectedTarget' => T_CONTINUE, + ], + 'Return should be start for contents of the return statement - contents' => [ + 'testMarker' => '/* testInsideCaseReturnStatement */', + 'targets' => T_FALSE, + 'expectedTarget' => T_RETURN, + ], + 'Exit should be start for contents of the exit statement - close parenthesis' => [ + // Note: not sure if this is actually correct - should this be the open parenthesis ? + 'testMarker' => '/* testInsideCaseExitStatement */', + 'targets' => T_CLOSE_PARENTHESIS, + 'expectedTarget' => T_EXIT, + ], + 'Throw should be start for contents of the throw statement - new keyword' => [ + 'testMarker' => '/* testInsideCaseThrowStatement */', + 'targets' => T_NEW, + 'expectedTarget' => T_THROW, + ], + 'Throw should be start for contents of the throw statement - exception name' => [ + 'testMarker' => '/* testInsideCaseThrowStatement */', + 'targets' => T_STRING, + 'expectedTarget' => T_THROW, + ], + 'Throw should be start for contents of the throw statement - close parenthesis' => [ + 'testMarker' => '/* testInsideCaseThrowStatement */', + 'targets' => T_CLOSE_PARENTHESIS, + 'expectedTarget' => T_THROW, + ], + 'Default keyword should be start of default statement - default itself' => [ + 'testMarker' => '/* testDefaultStatement */', + 'targets' => T_DEFAULT, + 'expectedTarget' => T_DEFAULT, + ], + 'Return should be start for contents of the return statement (inside default) - variable' => [ + 'testMarker' => '/* testInsideDefaultContinueStatement */', + 'targets' => T_VARIABLE, + 'expectedTarget' => T_CONTINUE, + ], + ]; + + }//end dataFindStartInsideSwitchCaseDefaultStatements() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetClassPropertiesTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetClassPropertiesTest.inc new file mode 100644 index 0000000..2490a09 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetClassPropertiesTest.inc @@ -0,0 +1,58 @@ + + * @copyright 2022 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:getClassProperties method. + * + * @covers \PHP_CodeSniffer\Files\File::getClassProperties + */ +class GetClassPropertiesTest extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an expected exception when a non class token is passed. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $tokenType The type of token to look for after the marker. + * + * @dataProvider dataNotAClassException + * + * @return void + */ + public function testNotAClassException($testMarker, $tokenType) + { + $this->expectRunTimeException('$stackPtr must be of type T_CLASS'); + + $target = $this->getTargetToken($testMarker, $tokenType); + self::$phpcsFile->getClassProperties($target); + + }//end testNotAClassException() + + + /** + * Data provider. + * + * @see testNotAClassException() For the array format. + * + * @return array> + */ + public function dataNotAClassException() + { + return [ + 'interface' => [ + 'testMarker' => '/* testNotAClass */', + 'tokenType' => \T_INTERFACE, + ], + 'anon-class' => [ + 'testMarker' => '/* testAnonClass */', + 'tokenType' => \T_ANON_CLASS, + ], + 'enum' => [ + 'testMarker' => '/* testEnum */', + 'tokenType' => \T_ENUM, + ], + ]; + + }//end dataNotAClassException() + + + /** + * Test retrieving the properties for a class declaration. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param array $expected Expected function output. + * + * @dataProvider dataGetClassProperties + * + * @return void + */ + public function testGetClassProperties($testMarker, $expected) + { + $class = $this->getTargetToken($testMarker, \T_CLASS); + $result = self::$phpcsFile->getClassProperties($class); + $this->assertSame($expected, $result); + + }//end testGetClassProperties() + + + /** + * Data provider. + * + * @see testGetClassProperties() For the array format. + * + * @return array>> + */ + public function dataGetClassProperties() + { + return [ + 'no-properties' => [ + 'testMarker' => '/* testClassWithoutProperties */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => false, + 'is_readonly' => false, + ], + ], + 'abstract' => [ + 'testMarker' => '/* testAbstractClass */', + 'expected' => [ + 'is_abstract' => true, + 'is_final' => false, + 'is_readonly' => false, + ], + ], + 'final' => [ + 'testMarker' => '/* testFinalClass */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => true, + 'is_readonly' => false, + ], + ], + 'readonly' => [ + 'testMarker' => '/* testReadonlyClass */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => false, + 'is_readonly' => true, + ], + ], + 'final-readonly' => [ + 'testMarker' => '/* testFinalReadonlyClass */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => true, + 'is_readonly' => true, + ], + ], + 'readonly-final' => [ + 'testMarker' => '/* testReadonlyFinalClass */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => true, + 'is_readonly' => true, + ], + ], + 'abstract-readonly' => [ + 'testMarker' => '/* testAbstractReadonlyClass */', + 'expected' => [ + 'is_abstract' => true, + 'is_final' => false, + 'is_readonly' => true, + ], + ], + 'readonly-abstract' => [ + 'testMarker' => '/* testReadonlyAbstractClass */', + 'expected' => [ + 'is_abstract' => true, + 'is_final' => false, + 'is_readonly' => true, + ], + ], + 'comments-and-new-lines' => [ + 'testMarker' => '/* testWithCommentsAndNewLines */', + 'expected' => [ + 'is_abstract' => true, + 'is_final' => false, + 'is_readonly' => false, + ], + ], + 'no-properties-with-docblock' => [ + 'testMarker' => '/* testWithDocblockWithoutProperties */', + 'expected' => [ + 'is_abstract' => false, + 'is_final' => false, + 'is_readonly' => false, + ], + ], + 'abstract-final-parse-error' => [ + 'testMarker' => '/* testParseErrorAbstractFinal */', + 'expected' => [ + 'is_abstract' => true, + 'is_final' => true, + 'is_readonly' => false, + ], + ], + ]; + + }//end dataGetClassProperties() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.inc new file mode 100644 index 0000000..e7684da --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.inc @@ -0,0 +1,91 @@ + $v) { + + /* condition 11-2: try */ + try { + --$k; + + /* condition 11-3: catch */ + } catch (Exception $e) { + /* testInException */ + echo 'oh darn'; + /* condition 11-4: finally */ + } finally { + return true; + } + } + + $a++; + } + break; + + /* condition 8b: default */ + default: + /* testInDefault */ + $return = 'nada'; + return $return; + } + } + } + } + } + } + } +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.php new file mode 100644 index 0000000..e6b0119 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetConditionTest.php @@ -0,0 +1,494 @@ + + * @copyright 2022-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:getCondition and \PHP_CodeSniffer\Files\File:hasCondition methods. + * + * @covers \PHP_CodeSniffer\Files\File::getCondition + * @covers \PHP_CodeSniffer\Files\File::hasCondition + */ +class GetConditionTest extends AbstractMethodUnitTest +{ + + /** + * List of all the test markers with their target token in the test case file. + * + * - The startPoint token is left out as it is tested separately. + * - The key is the type of token to look for after the test marker. + * + * @var array + */ + protected static $testTargets = [ + T_VARIABLE => '/* testSeriouslyNestedMethod */', + T_RETURN => '/* testDeepestNested */', + T_ECHO => '/* testInException */', + T_CONSTANT_ENCAPSED_STRING => '/* testInDefault */', + ]; + + /** + * List of all the condition markers in the test case file. + * + * @var array + */ + protected $conditionMarkers = [ + '/* condition 0: namespace */', + '/* condition 1: if */', + '/* condition 2: function */', + '/* condition 3-1: if */', + '/* condition 3-2: else */', + '/* condition 4: if */', + '/* condition 5: nested class */', + '/* condition 6: class method */', + '/* condition 7: switch */', + '/* condition 8a: case */', + '/* condition 9: while */', + '/* condition 10-1: if */', + '/* condition 11-1: nested anonymous class */', + '/* condition 12: nested anonymous class method */', + '/* condition 13: closure */', + '/* condition 10-2: elseif */', + '/* condition 10-3: foreach */', + '/* condition 11-2: try */', + '/* condition 11-3: catch */', + '/* condition 11-4: finally */', + '/* condition 8b: default */', + ]; + + /** + * Base array with all the scope opening tokens. + * + * This array is merged with expected result arrays for various unit tests + * to make sure all possible conditions are tested. + * + * This array should be kept in sync with the Tokens::$scopeOpeners array. + * This array isn't auto-generated based on the array in Tokens as for these + * tests we want to have access to the token constant names, not just their values. + * + * @var array + */ + protected $conditionDefaults = [ + 'T_CLASS' => false, + 'T_ANON_CLASS' => false, + 'T_INTERFACE' => false, + 'T_TRAIT' => false, + 'T_NAMESPACE' => false, + 'T_FUNCTION' => false, + 'T_CLOSURE' => false, + 'T_IF' => false, + 'T_SWITCH' => false, + 'T_CASE' => false, + 'T_DECLARE' => false, + 'T_DEFAULT' => false, + 'T_WHILE' => false, + 'T_ELSE' => false, + 'T_ELSEIF' => false, + 'T_FOR' => false, + 'T_FOREACH' => false, + 'T_DO' => false, + 'T_TRY' => false, + 'T_CATCH' => false, + 'T_FINALLY' => false, + 'T_PROPERTY' => false, + 'T_OBJECT' => false, + 'T_USE' => false, + ]; + + /** + * Cache for the test token stack pointers. + * + * @var array + */ + protected static $testTokens = []; + + /** + * Cache for the marker token stack pointers. + * + * @var array + */ + protected static $markerTokens = []; + + + /** + * Set up the token position caches for the tests. + * + * Retrieves the test tokens and marker token stack pointer positions + * only once and caches them as they won't change between the tests anyway. + * + * @before + * + * @return void + */ + protected function setUpCaches() + { + if (empty(self::$testTokens) === true) { + foreach (self::$testTargets as $targetToken => $marker) { + self::$testTokens[$marker] = $this->getTargetToken($marker, $targetToken); + } + } + + if (empty(self::$markerTokens) === true) { + foreach ($this->conditionMarkers as $marker) { + self::$markerTokens[$marker] = $this->getTargetToken($marker, Tokens::$scopeOpeners); + } + } + + }//end setUpCaches() + + + /** + * Test passing a non-existent token pointer. + * + * @return void + */ + public function testNonExistentToken() + { + $result = self::$phpcsFile->getCondition(100000, Tokens::$ooScopeTokens); + $this->assertFalse($result); + + $result = self::$phpcsFile->hasCondition(100000, T_IF); + $this->assertFalse($result); + + }//end testNonExistentToken() + + + /** + * Test passing a non conditional token. + * + * @return void + */ + public function testNonConditionalToken() + { + $targetType = T_STRING; + $stackPtr = $this->getTargetToken('/* testStartPoint */', $targetType); + + $result = self::$phpcsFile->getCondition($stackPtr, T_IF); + $this->assertFalse($result); + + $result = self::$phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens); + $this->assertFalse($result); + + }//end testNonConditionalToken() + + + /** + * Test retrieving a specific condition from a tokens "conditions" array. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param array $expectedResults Array with the condition token type to search for as key + * and the marker for the expected stack pointer result as a value. + * + * @dataProvider dataGetCondition + * + * @return void + */ + public function testGetCondition($testMarker, $expectedResults) + { + $stackPtr = self::$testTokens[$testMarker]; + + // Add expected results for all test markers not listed in the data provider. + $expectedResults += $this->conditionDefaults; + + foreach ($expectedResults as $conditionType => $expected) { + if (is_string($expected) === true) { + $expected = self::$markerTokens[$expected]; + } + + $result = self::$phpcsFile->getCondition($stackPtr, constant($conditionType)); + $this->assertSame( + $expected, + $result, + "Assertion failed for test marker '{$testMarker}' with condition {$conditionType}" + ); + } + + }//end testGetCondition() + + + /** + * Data provider. + * + * Only the conditions which are expected to be *found* need to be listed here. + * All other potential conditions will automatically also be tested and will expect + * `false` as a result. + * + * @see testGetCondition() For the array format. + * + * @return array>> + */ + public static function dataGetCondition() + { + return [ + 'testSeriouslyNestedMethod' => [ + 'testMarker' => '/* testSeriouslyNestedMethod */', + 'expectedResults' => [ + 'T_CLASS' => '/* condition 5: nested class */', + 'T_NAMESPACE' => '/* condition 0: namespace */', + 'T_FUNCTION' => '/* condition 2: function */', + 'T_IF' => '/* condition 1: if */', + 'T_ELSE' => '/* condition 3-2: else */', + ], + ], + 'testDeepestNested' => [ + 'testMarker' => '/* testDeepestNested */', + 'expectedResults' => [ + 'T_CLASS' => '/* condition 5: nested class */', + 'T_ANON_CLASS' => '/* condition 11-1: nested anonymous class */', + 'T_NAMESPACE' => '/* condition 0: namespace */', + 'T_FUNCTION' => '/* condition 2: function */', + 'T_CLOSURE' => '/* condition 13: closure */', + 'T_IF' => '/* condition 1: if */', + 'T_SWITCH' => '/* condition 7: switch */', + 'T_CASE' => '/* condition 8a: case */', + 'T_WHILE' => '/* condition 9: while */', + 'T_ELSE' => '/* condition 3-2: else */', + ], + ], + 'testInException' => [ + 'testMarker' => '/* testInException */', + 'expectedResults' => [ + 'T_CLASS' => '/* condition 5: nested class */', + 'T_NAMESPACE' => '/* condition 0: namespace */', + 'T_FUNCTION' => '/* condition 2: function */', + 'T_IF' => '/* condition 1: if */', + 'T_SWITCH' => '/* condition 7: switch */', + 'T_CASE' => '/* condition 8a: case */', + 'T_WHILE' => '/* condition 9: while */', + 'T_ELSE' => '/* condition 3-2: else */', + 'T_FOREACH' => '/* condition 10-3: foreach */', + 'T_CATCH' => '/* condition 11-3: catch */', + ], + ], + 'testInDefault' => [ + 'testMarker' => '/* testInDefault */', + 'expectedResults' => [ + 'T_CLASS' => '/* condition 5: nested class */', + 'T_NAMESPACE' => '/* condition 0: namespace */', + 'T_FUNCTION' => '/* condition 2: function */', + 'T_IF' => '/* condition 1: if */', + 'T_SWITCH' => '/* condition 7: switch */', + 'T_DEFAULT' => '/* condition 8b: default */', + 'T_ELSE' => '/* condition 3-2: else */', + ], + ], + ]; + + }//end dataGetCondition() + + + /** + * Test retrieving a specific condition from a tokens "conditions" array. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param array $expectedResults Array with the condition token type to search for as key + * and the marker for the expected stack pointer result as a value. + * + * @dataProvider dataGetConditionReversed + * + * @return void + */ + public function testGetConditionReversed($testMarker, $expectedResults) + { + $stackPtr = self::$testTokens[$testMarker]; + + // Add expected results for all test markers not listed in the data provider. + $expectedResults += $this->conditionDefaults; + + foreach ($expectedResults as $conditionType => $expected) { + if (is_string($expected) === true) { + $expected = self::$markerTokens[$expected]; + } + + $result = self::$phpcsFile->getCondition($stackPtr, constant($conditionType), false); + $this->assertSame( + $expected, + $result, + "Assertion failed for test marker '{$testMarker}' with condition {$conditionType} (reversed)" + ); + } + + }//end testGetConditionReversed() + + + /** + * Data provider. + * + * Only the conditions which are expected to be *found* need to be listed here. + * All other potential conditions will automatically also be tested and will expect + * `false` as a result. + * + * @see testGetConditionReversed() For the array format. + * + * @return array>> + */ + public static function dataGetConditionReversed() + { + $data = self::dataGetCondition(); + + // Set up the data for the reversed results. + $data['testSeriouslyNestedMethod']['expectedResults']['T_IF'] = '/* condition 4: if */'; + + $data['testDeepestNested']['expectedResults']['T_FUNCTION'] = '/* condition 12: nested anonymous class method */'; + $data['testDeepestNested']['expectedResults']['T_IF'] = '/* condition 10-1: if */'; + + $data['testInException']['expectedResults']['T_FUNCTION'] = '/* condition 6: class method */'; + $data['testInException']['expectedResults']['T_IF'] = '/* condition 4: if */'; + + $data['testInDefault']['expectedResults']['T_FUNCTION'] = '/* condition 6: class method */'; + $data['testInDefault']['expectedResults']['T_IF'] = '/* condition 4: if */'; + + return $data; + + }//end dataGetConditionReversed() + + + /** + * Test whether a token has a condition of a certain type. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param array $expectedResults Array with the condition token type to search for as key + * and the expected result as a value. + * + * @dataProvider dataHasCondition + * + * @return void + */ + public function testHasCondition($testMarker, $expectedResults) + { + $stackPtr = self::$testTokens[$testMarker]; + + // Add expected results for all test markers not listed in the data provider. + $expectedResults += $this->conditionDefaults; + + foreach ($expectedResults as $conditionType => $expected) { + $result = self::$phpcsFile->hasCondition($stackPtr, constant($conditionType)); + $this->assertSame( + $expected, + $result, + "Assertion failed for test marker '{$testMarker}' with condition {$conditionType}" + ); + } + + }//end testHasCondition() + + + /** + * Data Provider. + * + * Only list the "true" conditions in the $results array. + * All other potential conditions will automatically also be tested + * and will expect "false" as a result. + * + * @see testHasCondition() For the array format. + * + * @return array>> + */ + public static function dataHasCondition() + { + return [ + 'testSeriouslyNestedMethod' => [ + 'testMarker' => '/* testSeriouslyNestedMethod */', + 'expectedResults' => [ + 'T_CLASS' => true, + 'T_NAMESPACE' => true, + 'T_FUNCTION' => true, + 'T_IF' => true, + 'T_ELSE' => true, + ], + ], + 'testDeepestNested' => [ + 'testMarker' => '/* testDeepestNested */', + 'expectedResults' => [ + 'T_CLASS' => true, + 'T_ANON_CLASS' => true, + 'T_NAMESPACE' => true, + 'T_FUNCTION' => true, + 'T_CLOSURE' => true, + 'T_IF' => true, + 'T_SWITCH' => true, + 'T_CASE' => true, + 'T_WHILE' => true, + 'T_ELSE' => true, + ], + ], + 'testInException' => [ + 'testMarker' => '/* testInException */', + 'expectedResults' => [ + 'T_CLASS' => true, + 'T_NAMESPACE' => true, + 'T_FUNCTION' => true, + 'T_IF' => true, + 'T_SWITCH' => true, + 'T_CASE' => true, + 'T_WHILE' => true, + 'T_ELSE' => true, + 'T_FOREACH' => true, + 'T_CATCH' => true, + ], + ], + 'testInDefault' => [ + 'testMarker' => '/* testInDefault */', + 'expectedResults' => [ + 'T_CLASS' => true, + 'T_NAMESPACE' => true, + 'T_FUNCTION' => true, + 'T_IF' => true, + 'T_SWITCH' => true, + 'T_DEFAULT' => true, + 'T_ELSE' => true, + ], + ], + ]; + + }//end dataHasCondition() + + + /** + * Test whether a token has a condition of a certain type, with multiple allowed possibilities. + * + * @return void + */ + public function testHasConditionMultipleTypes() + { + $stackPtr = self::$testTokens['/* testInException */']; + + $result = self::$phpcsFile->hasCondition($stackPtr, [T_TRY, T_FINALLY]); + $this->assertFalse( + $result, + 'Failed asserting that "testInException" does not have a "try" nor a "finally" condition' + ); + + $result = self::$phpcsFile->hasCondition($stackPtr, [T_TRY, T_CATCH, T_FINALLY]); + $this->assertTrue( + $result, + 'Failed asserting that "testInException" has a "try", "catch" or "finally" condition' + ); + + $stackPtr = self::$testTokens['/* testSeriouslyNestedMethod */']; + + $result = self::$phpcsFile->hasCondition($stackPtr, [T_ANON_CLASS, T_CLOSURE]); + $this->assertFalse( + $result, + 'Failed asserting that "testSeriouslyNestedMethod" does not have an anonymous class nor a closure condition' + ); + + $result = self::$phpcsFile->hasCondition($stackPtr, Tokens::$ooScopeTokens); + $this->assertTrue( + $result, + 'Failed asserting that "testSeriouslyNestedMethod" has an OO Scope token condition' + ); + + }//end testHasConditionMultipleTypes() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.js b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.js new file mode 100644 index 0000000..ee0a76a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.js @@ -0,0 +1,23 @@ +/* testInvalidTokenPassed */ +print something; + +var object = +{ + /* testClosure */ + propertyName: function () {} +} + +/* testFunction */ +function functionName() {} + +/* testClass */ +class ClassName +{ + /* testMethod */ + methodName() { + return false; + } +} + +/* testFunctionUnicode */ +function π() {} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.php new file mode 100644 index 0000000..a2b8968 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameJSTest.php @@ -0,0 +1,158 @@ + + * @copyright 2022-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:getDeclarationName method. + * + * @covers \PHP_CodeSniffer\Files\File::getDeclarationName + */ +class GetDeclarationNameJSTest extends AbstractMethodUnitTest +{ + + /** + * The file extension of the test case file (without leading dot). + * + * @var string + */ + protected static $fileExtension = 'js'; + + + /** + * Test receiving an expected exception when a non-supported token is passed. + * + * @return void + */ + public function testInvalidTokenPassed() + { + $this->expectRunTimeException('Token type "T_STRING" is not T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM'); + + $target = $this->getTargetToken('/* testInvalidTokenPassed */', T_STRING); + self::$phpcsFile->getDeclarationName($target); + + }//end testInvalidTokenPassed() + + + /** + * Test receiving "null" when passed an anonymous construct or in case of a parse error. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $targetType Token type of the token to get as stackPtr. + * + * @dataProvider dataGetDeclarationNameNull + * + * @return void + */ + public function testGetDeclarationNameNull($testMarker, $targetType) + { + $target = $this->getTargetToken($testMarker, $targetType); + $result = self::$phpcsFile->getDeclarationName($target); + $this->assertNull($result); + + }//end testGetDeclarationNameNull() + + + /** + * Data provider. + * + * @see GetDeclarationNameTest::testGetDeclarationNameNull() + * + * @return array> + */ + public static function dataGetDeclarationNameNull() + { + return [ + 'closure' => [ + 'testMarker' => '/* testClosure */', + 'targetType' => T_CLOSURE, + ], + ]; + + }//end dataGetDeclarationNameNull() + + + /** + * Test retrieving the name of a function or OO structure. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expected Expected function output. + * @param array|null $targetType Token type of the token to get as stackPtr. + * + * @dataProvider dataGetDeclarationName + * + * @return void + */ + public function testGetDeclarationName($testMarker, $expected, $targetType=null) + { + if (isset($targetType) === false) { + $targetType = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + ]; + } + + $target = $this->getTargetToken($testMarker, $targetType); + $result = self::$phpcsFile->getDeclarationName($target); + $this->assertSame($expected, $result); + + }//end testGetDeclarationName() + + + /** + * Data provider. + * + * @see GetDeclarationNameTest::testGetDeclarationName() + * + * @return array>> + */ + public static function dataGetDeclarationName() + { + return [ + 'function' => [ + 'testMarker' => '/* testFunction */', + 'expected' => 'functionName', + ], + 'class' => [ + 'testMarker' => '/* testClass */', + 'expected' => 'ClassName', + 'targetType' => [ + T_CLASS, + T_STRING, + ], + ], + 'function-unicode-name' => [ + 'testMarker' => '/* testFunctionUnicode */', + 'expected' => 'π', + ], + ]; + + }//end dataGetDeclarationName() + + + /** + * Test retrieving the name of JS ES6 class method. + * + * @return void + */ + public function testGetDeclarationNameES6Method() + { + $target = $this->getTargetToken('/* testMethod */', [T_CLASS, T_INTERFACE, T_TRAIT, T_FUNCTION]); + $result = self::$phpcsFile->getDeclarationName($target); + $this->assertSame('methodName', $result); + + }//end testGetDeclarationNameES6Method() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameTest.inc new file mode 100644 index 0000000..1490224 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetDeclarationNameTest.inc @@ -0,0 +1,102 @@ + + * @copyright 2022-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:getDeclarationName method. + * + * @covers \PHP_CodeSniffer\Files\File::getDeclarationName + */ +class GetDeclarationNameTest extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an expected exception when a non-supported token is passed. + * + * @return void + */ + public function testInvalidTokenPassed() + { + $this->expectRunTimeException('Token type "T_STRING" is not T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM'); + + $target = $this->getTargetToken('/* testInvalidTokenPassed */', T_STRING); + self::$phpcsFile->getDeclarationName($target); + + }//end testInvalidTokenPassed() + + + /** + * Test receiving "null" when passed an anonymous construct or in case of a parse error. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $targetType Token type of the token to get as stackPtr. + * + * @dataProvider dataGetDeclarationNameNull + * + * @return void + */ + public function testGetDeclarationNameNull($testMarker, $targetType) + { + $target = $this->getTargetToken($testMarker, $targetType); + $result = self::$phpcsFile->getDeclarationName($target); + $this->assertNull($result); + + }//end testGetDeclarationNameNull() + + + /** + * Data provider. + * + * @see testGetDeclarationNameNull() For the array format. + * + * @return array> + */ + public static function dataGetDeclarationNameNull() + { + return [ + 'closure' => [ + 'testMarker' => '/* testClosure */', + 'targetType' => T_CLOSURE, + ], + 'anon-class-with-parentheses' => [ + 'testMarker' => '/* testAnonClassWithParens */', + 'targetType' => T_ANON_CLASS, + ], + 'anon-class-with-parentheses-2' => [ + 'testMarker' => '/* testAnonClassWithParens2 */', + 'targetType' => T_ANON_CLASS, + ], + 'anon-class-without-parentheses' => [ + 'testMarker' => '/* testAnonClassWithoutParens */', + 'targetType' => T_ANON_CLASS, + ], + 'anon-class-extends-without-parentheses' => [ + 'testMarker' => '/* testAnonClassExtendsWithoutParens */', + 'targetType' => T_ANON_CLASS, + ], + 'live-coding' => [ + 'testMarker' => '/* testLiveCoding */', + 'targetType' => T_FUNCTION, + ], + ]; + + }//end dataGetDeclarationNameNull() + + + /** + * Test retrieving the name of a function or OO structure. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expected Expected function output. + * @param int|string|null $targetType Token type of the token to get as stackPtr. + * + * @dataProvider dataGetDeclarationName + * + * @return void + */ + public function testGetDeclarationName($testMarker, $expected, $targetType=null) + { + if (isset($targetType) === false) { + $targetType = [ + T_CLASS, + T_INTERFACE, + T_TRAIT, + T_ENUM, + T_FUNCTION, + ]; + } + + $target = $this->getTargetToken($testMarker, $targetType); + $result = self::$phpcsFile->getDeclarationName($target); + $this->assertSame($expected, $result); + + }//end testGetDeclarationName() + + + /** + * Data provider. + * + * @see testGetDeclarationName() For the array format. + * + * @return array> + */ + public static function dataGetDeclarationName() + { + return [ + 'function' => [ + 'testMarker' => '/* testFunction */', + 'expected' => 'functionName', + ], + 'function-return-by-reference' => [ + 'testMarker' => '/* testFunctionReturnByRef */', + 'expected' => 'functionNameByRef', + ], + 'class' => [ + 'testMarker' => '/* testClass */', + 'expected' => 'ClassName', + ], + 'method' => [ + 'testMarker' => '/* testMethod */', + 'expected' => 'methodName', + ], + 'abstract-method' => [ + 'testMarker' => '/* testAbstractMethod */', + 'expected' => 'abstractMethodName', + ], + 'method-return-by-reference' => [ + 'testMarker' => '/* testMethodReturnByRef */', + 'expected' => 'MethodNameByRef', + ], + 'extended-class' => [ + 'testMarker' => '/* testExtendedClass */', + 'expected' => 'ExtendedClass', + ], + 'interface' => [ + 'testMarker' => '/* testInterface */', + 'expected' => 'InterfaceName', + ], + 'trait' => [ + 'testMarker' => '/* testTrait */', + 'expected' => 'TraitName', + ], + 'function-name-ends-with-number' => [ + 'testMarker' => '/* testFunctionEndingWithNumber */', + 'expected' => 'ValidNameEndingWithNumber5', + ], + 'class-with-numbers-in-name' => [ + 'testMarker' => '/* testClassWithNumber */', + 'expected' => 'ClassWith1Number', + ], + 'interface-with-numbers-in-name' => [ + 'testMarker' => '/* testInterfaceWithNumbers */', + 'expected' => 'InterfaceWith12345Numbers', + ], + 'class-with-comments-and-new-lines' => [ + 'testMarker' => '/* testClassWithCommentsAndNewLines */', + 'expected' => 'ClassWithCommentsAndNewLines', + ], + 'function-named-fn' => [ + 'testMarker' => '/* testFunctionFn */', + 'expected' => 'fn', + ], + 'enum-pure' => [ + 'testMarker' => '/* testPureEnum */', + 'expected' => 'Foo', + ], + 'enum-backed-space-between-name-and-colon' => [ + 'testMarker' => '/* testBackedEnumSpaceBetweenNameAndColon */', + 'expected' => 'Hoo', + ], + 'enum-backed-no-space-between-name-and-colon' => [ + 'testMarker' => '/* testBackedEnumNoSpaceBetweenNameAndColon */', + 'expected' => 'Suit', + ], + 'function-return-by-reference-with-reserved-keyword-each' => [ + 'testMarker' => '/* testFunctionReturnByRefWithReservedKeywordEach */', + 'expected' => 'each', + ], + 'function-return-by-reference-with-reserved-keyword-parent' => [ + 'testMarker' => '/* testFunctionReturnByRefWithReservedKeywordParent */', + 'expected' => 'parent', + ], + 'function-return-by-reference-with-reserved-keyword-self' => [ + 'testMarker' => '/* testFunctionReturnByRefWithReservedKeywordSelf */', + 'expected' => 'self', + ], + 'function-return-by-reference-with-reserved-keyword-static' => [ + 'testMarker' => '/* testFunctionReturnByRefWithReservedKeywordStatic */', + 'expected' => 'static', + ], + ]; + + }//end dataGetDeclarationName() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.inc new file mode 100644 index 0000000..f69a685 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.inc @@ -0,0 +1,341 @@ + 'a', 'b' => 'b' ), + /* testGroupPrivate 3 */ + $varQ = 'string', + /* testGroupPrivate 4 */ + $varR = 123, + /* testGroupPrivate 5 */ + $varS = ONE / self::THREE, + /* testGroupPrivate 6 */ + $varT = [ + 'a' => 'a', + 'b' => 'b' + ], + /* testGroupPrivate 7 */ + $varU = __DIR__ . "/base"; + + + /* testMethodParam */ + public function methodName($param) { + /* testImportedGlobal */ + global $importedGlobal = true; + + /* testLocalVariable */ + $localVariable = true; + } + + /* testPropertyAfterMethod */ + private static $varV = true; + + /* testMessyNullableType */ + public /* comment + */ ? //comment + array $foo = []; + + /* testNamespaceType */ + public \MyNamespace\MyClass $foo; + + /* testNullableNamespaceType 1 */ + private ?ClassName $nullableClassType; + + /* testNullableNamespaceType 2 */ + protected ?Folder\ClassName $nullableClassType2; + + /* testMultilineNamespaceType */ + public \MyNamespace /** comment *\/ comment */ + \MyClass /* comment */ + \Foo $foo; + +} + +interface Base +{ + /* testInterfaceProperty */ + protected $anonymous; +} + +/* testGlobalVariable */ +$globalVariable = true; + +/* testNotAVariable */ +return; + +$a = ( $foo == $bar ? new stdClass() : + new class() { + /* testNestedProperty 1 */ + public $var = true; + + /* testNestedMethodParam 1 */ + public function something($var = false) {} + } +); + +function_call( 'param', new class { + /* testNestedProperty 2 */ + public $year = 2017; + + /* testNestedMethodParam 2 */ + public function __construct( $open, $post_id ) {} +}, 10, 2 ); + +class PHP8Mixed { + /* testPHP8MixedTypeHint */ + public static miXed $mixed; + + /* testPHP8MixedTypeHintNullable */ + // Intentional fatal error - nullability is not allowed with mixed, but that's not the concern of the method. + private ?mixed $nullableMixed; +} + +class NSOperatorInType { + /* testNamespaceOperatorTypeHint */ + public ?namespace\Name $prop; +} + +$anon = class() { + /* testPHP8UnionTypesSimple */ + public int|float $unionTypeSimple; + + /* testPHP8UnionTypesTwoClasses */ + private MyClassA|\Package\MyClassB $unionTypesTwoClasses; + + /* testPHP8UnionTypesAllBaseTypes */ + protected array|bool|int|float|NULL|object|string $unionTypesAllBaseTypes; + + /* testPHP8UnionTypesAllPseudoTypes */ + // Intentional fatal error - mixing types which cannot be combined, but that's not the concern of the method. + var false|mixed|self|parent|iterable|Resource $unionTypesAllPseudoTypes; + + /* testPHP8UnionTypesIllegalTypes */ + // Intentional fatal error - types which are not allowed for properties, but that's not the concern of the method. + // Note: static is also not allowed as a type, but using static for a property type is not supported by the tokenizer. + public callable|void $unionTypesIllegalTypes; + + /* testPHP8UnionTypesNullable */ + // Intentional fatal error - nullability is not allowed with union types, but that's not the concern of the method. + public ?int|float $unionTypesNullable; + + /* testPHP8PseudoTypeNull */ + // PHP 8.0 - 8.1: Intentional fatal error - null pseudotype is only allowed in union types, but that's not the concern of the method. + public null $pseudoTypeNull; + + /* testPHP8PseudoTypeFalse */ + // PHP 8.0 - 8.1: Intentional fatal error - false pseudotype is only allowed in union types, but that's not the concern of the method. + public false $pseudoTypeFalse; + + /* testPHP8PseudoTypeFalseAndBool */ + // Intentional fatal error - false pseudotype is not allowed in combination with bool, but that's not the concern of the method. + public bool|FALSE $pseudoTypeFalseAndBool; + + /* testPHP8ObjectAndClass */ + // Intentional fatal error - object is not allowed in combination with class name, but that's not the concern of the method. + public object|ClassName $objectAndClass; + + /* testPHP8PseudoTypeIterableAndArray */ + // Intentional fatal error - iterable pseudotype is not allowed in combination with array or Traversable, but that's not the concern of the method. + public iterable|array|Traversable $pseudoTypeIterableAndArray; + + /* testPHP8DuplicateTypeInUnionWhitespaceAndComment */ + // Intentional fatal error - duplicate types are not allowed in union types, but that's not the concern of the method. + public int |string| /*comment*/ INT $duplicateTypeInUnion; + + /* testPHP81Readonly */ + public readonly int $readonly; + + /* testPHP81ReadonlyWithNullableType */ + public readonly ?array $readonlyWithNullableType; + + /* testPHP81ReadonlyWithUnionType */ + public readonly string|int $readonlyWithUnionType; + + /* testPHP81ReadonlyWithUnionTypeWithNull */ + protected ReadOnly string|null $readonlyWithUnionTypeWithNull; + + /* testPHP81OnlyReadonlyWithUnionType */ + readonly string|int $onlyReadonly; + + /* testPHP81OnlyReadonlyWithUnionTypeMultiple */ + readonly \InterfaceA|\Sub\InterfaceB|false + $onlyReadonly; + + /* testPHP81ReadonlyAndStatic */ + readonly private static ?string $readonlyAndStatic; + + /* testPHP81ReadonlyMixedCase */ + public ReadONLY static $readonlyMixedCase; +}; + +$anon = class { + /* testPHP8PropertySingleAttribute */ + #[PropertyWithAttribute] + public string $foo; + + /* testPHP8PropertyMultipleAttributes */ + #[PropertyWithAttribute(foo: 'bar'), MyAttribute] + protected ?int|float $bar; + + /* testPHP8PropertyMultilineAttribute */ + #[ + PropertyWithAttribute(/* comment */ 'baz') + ] + private mixed $baz; +}; + +enum Suit +{ + /* testEnumProperty */ + protected $anonymous; +} + +enum Direction implements ArrayAccess +{ + case Up; + case Down; + + /* testEnumMethodParamNotProperty */ + public function offsetGet($val) { ... } +} + +$anon = class() { + /* testPHP81IntersectionTypes */ + public Foo&Bar $intersectionType; + + /* testPHP81MoreIntersectionTypes */ + public Foo&Bar&Baz $moreIntersectionTypes; + + /* testPHP81IllegalIntersectionTypes */ + // Intentional fatal error - types which are not allowed for intersection type, but that's not the concern of the method. + public int&string $illegalIntersectionType; + + /* testPHP81NullableIntersectionType */ + // Intentional fatal error - nullability is not allowed with intersection type, but that's not the concern of the method. + public ?Foo&Bar $nullableIntersectionType; +}; + +$anon = class() { + /* testPHP82PseudoTypeTrue */ + public true $pseudoTypeTrue; + + /* testPHP82NullablePseudoTypeTrue */ + static protected ?true $pseudoTypeNullableTrue; + + /* testPHP82PseudoTypeTrueInUnion */ + private int|string|true $pseudoTypeTrueInUnion; + + /* testPHP82PseudoTypeFalseAndTrue */ + // Intentional fatal error - Type contains both true and false, bool should be used instead, but that's not the concern of the method. + readonly true|FALSE $pseudoTypeFalseAndTrue; +}; + +class WhitespaceAndCommentsInTypes { + /* testUnionTypeWithWhitespaceAndComment */ + public int | /*comment*/ string $hasWhitespaceAndComment; + + /* testIntersectionTypeWithWhitespaceAndComment */ + public \Foo /*comment*/ & Bar $hasWhitespaceAndComment; +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.php new file mode 100644 index 0000000..24a170a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMemberPropertiesTest.php @@ -0,0 +1,1139 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::getMemberProperties method. + * + * @covers \PHP_CodeSniffer\Files\File::getMemberProperties + */ +class GetMemberPropertiesTest extends AbstractMethodUnitTest +{ + + + /** + * Test the getMemberProperties() method. + * + * @param string $identifier Comment which precedes the test case. + * @param array $expected Expected function output. + * + * @dataProvider dataGetMemberProperties + * + * @return void + */ + public function testGetMemberProperties($identifier, $expected) + { + $variable = $this->getTargetToken($identifier, T_VARIABLE); + $result = self::$phpcsFile->getMemberProperties($variable); + + // Convert offsets to absolute positions in the token stream. + if (isset($expected['type_token']) === true && is_int($expected['type_token']) === true) { + $expected['type_token'] += $variable; + } + + if (isset($expected['type_end_token']) === true && is_int($expected['type_end_token']) === true) { + $expected['type_end_token'] += $variable; + } + + $this->assertSame($expected, $result); + + }//end testGetMemberProperties() + + + /** + * Data provider for the GetMemberProperties test. + * + * Note: the `expected - type_token` and `expected - type_end_token` indexes should + * contain either `false` (no type) or the _offset_ of the type start/end token in + * relation to the `T_VARIABLE` token which is passed to the getMemberProperties() method. + * + * @see testGetMemberProperties() + * + * @return array>> + */ + public function dataGetMemberProperties() + { + return [ + 'var-modifier' => [ + 'identifier' => '/* testVar */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'var-modifier-and-type' => [ + 'identifier' => '/* testVarType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?int', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'public-modifier' => [ + 'identifier' => '/* testPublic */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'public-modifier-and-type' => [ + 'identifier' => '/* testPublicType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'string', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'protected-modifier' => [ + 'identifier' => '/* testProtected */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'protected-modifier-and-type' => [ + 'identifier' => '/* testProtectedType */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'bool', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'private-modifier' => [ + 'identifier' => '/* testPrivate */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'private-modifier-and-type' => [ + 'identifier' => '/* testPrivateType */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'array', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'static-modifier' => [ + 'identifier' => '/* testStatic */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'static-modifier-and-type' => [ + 'identifier' => '/* testStaticType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '?string', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'static-and-var-modifier' => [ + 'identifier' => '/* testStaticVar */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'var-and-static-modifier' => [ + 'identifier' => '/* testVarStatic */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'public-static-modifiers' => [ + 'identifier' => '/* testPublicStatic */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'protected-static-modifiers' => [ + 'identifier' => '/* testProtectedStatic */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'private-static-modifiers' => [ + 'identifier' => '/* testPrivateStatic */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'no-modifier' => [ + 'identifier' => '/* testNoPrefix */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'public-and-static-modifier-with-docblock' => [ + 'identifier' => '/* testPublicStaticWithDocblock */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'protected-and-static-modifier-with-docblock' => [ + 'identifier' => '/* testProtectedStaticWithDocblock */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'private-and-static-modifier-with-docblock' => [ + 'identifier' => '/* testPrivateStaticWithDocblock */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-simple-type-prop-1' => [ + 'identifier' => '/* testGroupType 1 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'float', + 'type_token' => -6, + 'type_end_token' => -6, + 'nullable_type' => false, + ], + ], + 'property-group-simple-type-prop-2' => [ + 'identifier' => '/* testGroupType 2 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'float', + 'type_token' => -13, + 'type_end_token' => -13, + 'nullable_type' => false, + ], + ], + 'property-group-nullable-type-prop-1' => [ + 'identifier' => '/* testGroupNullableType 1 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '?string', + 'type_token' => -6, + 'type_end_token' => -6, + 'nullable_type' => true, + ], + ], + 'property-group-nullable-type-prop-2' => [ + 'identifier' => '/* testGroupNullableType 2 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '?string', + 'type_token' => -17, + 'type_end_token' => -17, + 'nullable_type' => true, + ], + ], + 'property-group-protected-static-prop-1' => [ + 'identifier' => '/* testGroupProtectedStatic 1 */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-protected-static-prop-2' => [ + 'identifier' => '/* testGroupProtectedStatic 2 */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-protected-static-prop-3' => [ + 'identifier' => '/* testGroupProtectedStatic 3 */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-1' => [ + 'identifier' => '/* testGroupPrivate 1 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-2' => [ + 'identifier' => '/* testGroupPrivate 2 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-3' => [ + 'identifier' => '/* testGroupPrivate 3 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-4' => [ + 'identifier' => '/* testGroupPrivate 4 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-5' => [ + 'identifier' => '/* testGroupPrivate 5 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-6' => [ + 'identifier' => '/* testGroupPrivate 6 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-group-private-prop-7' => [ + 'identifier' => '/* testGroupPrivate 7 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'messy-nullable-type' => [ + 'identifier' => '/* testMessyNullableType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?array', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'fqn-type' => [ + 'identifier' => '/* testNamespaceType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '\MyNamespace\MyClass', + 'type_token' => -5, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'nullable-classname-type' => [ + 'identifier' => '/* testNullableNamespaceType 1 */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?ClassName', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'nullable-namespace-relative-class-type' => [ + 'identifier' => '/* testNullableNamespaceType 2 */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?Folder\ClassName', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'multiline-namespaced-type' => [ + 'identifier' => '/* testMultilineNamespaceType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '\MyNamespace\MyClass\Foo', + 'type_token' => -18, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'property-after-method' => [ + 'identifier' => '/* testPropertyAfterMethod */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'invalid-property-in-interface' => [ + 'identifier' => '/* testInterfaceProperty */', + 'expected' => [], + ], + 'property-in-nested-class-1' => [ + 'identifier' => '/* testNestedProperty 1 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'property-in-nested-class-2' => [ + 'identifier' => '/* testNestedProperty 2 */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'php8-mixed-type' => [ + 'identifier' => '/* testPHP8MixedTypeHint */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => 'miXed', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-nullable-mixed-type' => [ + 'identifier' => '/* testPHP8MixedTypeHintNullable */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?mixed', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'namespace-operator-type-declaration' => [ + 'identifier' => '/* testNamespaceOperatorTypeHint */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?namespace\Name', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8-union-types-simple' => [ + 'identifier' => '/* testPHP8UnionTypesSimple */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'int|float', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-two-classes' => [ + 'identifier' => '/* testPHP8UnionTypesTwoClasses */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'MyClassA|\Package\MyClassB', + 'type_token' => -7, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-all-base-types' => [ + 'identifier' => '/* testPHP8UnionTypesAllBaseTypes */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'array|bool|int|float|NULL|object|string', + 'type_token' => -14, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-all-pseudo-types' => [ + 'identifier' => '/* testPHP8UnionTypesAllPseudoTypes */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'false|mixed|self|parent|iterable|Resource', + 'type_token' => -12, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-illegal-types' => [ + 'identifier' => '/* testPHP8UnionTypesIllegalTypes */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + // Missing static, but that's OK as not an allowed syntax. + 'type' => 'callable|void', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-nullable' => [ + 'identifier' => '/* testPHP8UnionTypesNullable */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?int|float', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8-union-types-pseudo-type-null' => [ + 'identifier' => '/* testPHP8PseudoTypeNull */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'null', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-pseudo-type-false' => [ + 'identifier' => '/* testPHP8PseudoTypeFalse */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'false', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-pseudo-type-false-and-bool' => [ + 'identifier' => '/* testPHP8PseudoTypeFalseAndBool */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'bool|FALSE', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-object-and-class' => [ + 'identifier' => '/* testPHP8ObjectAndClass */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'object|ClassName', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-pseudo-type-iterable-and-array' => [ + 'identifier' => '/* testPHP8PseudoTypeIterableAndArray */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'iterable|array|Traversable', + 'type_token' => -6, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-union-types-duplicate-type-with-whitespace-and-comments' => [ + 'identifier' => '/* testPHP8DuplicateTypeInUnionWhitespaceAndComment */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'int|string|INT', + 'type_token' => -10, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-property' => [ + 'identifier' => '/* testPHP81Readonly */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => true, + 'type' => 'int', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-property-with-nullable-type' => [ + 'identifier' => '/* testPHP81ReadonlyWithNullableType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => true, + 'type' => '?array', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8.1-readonly-property-with-union-type' => [ + 'identifier' => '/* testPHP81ReadonlyWithUnionType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => true, + 'type' => 'string|int', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-property-with-union-type-with-null' => [ + 'identifier' => '/* testPHP81ReadonlyWithUnionTypeWithNull */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => true, + 'type' => 'string|null', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-property-with-union-type-no-visibility' => [ + 'identifier' => '/* testPHP81OnlyReadonlyWithUnionType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => true, + 'type' => 'string|int', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-property-with-multi-union-type-no-visibility' => [ + 'identifier' => '/* testPHP81OnlyReadonlyWithUnionTypeMultiple */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => true, + 'type' => '\InterfaceA|\Sub\InterfaceB|false', + 'type_token' => -11, + 'type_end_token' => -3, + 'nullable_type' => false, + ], + ], + 'php8.1-readonly-and-static-property' => [ + 'identifier' => '/* testPHP81ReadonlyAndStatic */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => true, + 'type' => '?string', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8.1-readonly-mixed-case-keyword' => [ + 'identifier' => '/* testPHP81ReadonlyMixedCase */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => true, + 'type' => '', + 'type_token' => false, + 'type_end_token' => false, + 'nullable_type' => false, + ], + ], + 'php8-property-with-single-attribute' => [ + 'identifier' => '/* testPHP8PropertySingleAttribute */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'string', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8-property-with-multiple-attributes' => [ + 'identifier' => '/* testPHP8PropertyMultipleAttributes */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?int|float', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8-property-with-multiline-attribute' => [ + 'identifier' => '/* testPHP8PropertyMultilineAttribute */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'mixed', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'invalid-property-in-enum' => [ + 'identifier' => '/* testEnumProperty */', + 'expected' => [], + ], + 'php8.1-single-intersection-type' => [ + 'identifier' => '/* testPHP81IntersectionTypes */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'Foo&Bar', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-multi-intersection-type' => [ + 'identifier' => '/* testPHP81MoreIntersectionTypes */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'Foo&Bar&Baz', + 'type_token' => -6, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-illegal-intersection-type' => [ + 'identifier' => '/* testPHP81IllegalIntersectionTypes */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'int&string', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-nullable-intersection-type' => [ + 'identifier' => '/* testPHP81NullableIntersectionType */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '?Foo&Bar', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + + 'php8.0-union-type-with-whitespace-and-comment' => [ + 'identifier' => '/* testUnionTypeWithWhitespaceAndComment */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'int|string', + 'type_token' => -8, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.1-intersection-type-with-whitespace-and-comment' => [ + 'identifier' => '/* testIntersectionTypeWithWhitespaceAndComment */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => '\Foo&Bar', + 'type_token' => -9, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.2-pseudo-type-true' => [ + 'identifier' => '/* testPHP82PseudoTypeTrue */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'true', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.2-pseudo-type-true-nullable' => [ + 'identifier' => '/* testPHP82NullablePseudoTypeTrue */', + 'expected' => [ + 'scope' => 'protected', + 'scope_specified' => true, + 'is_static' => true, + 'is_readonly' => false, + 'type' => '?true', + 'type_token' => -2, + 'type_end_token' => -2, + 'nullable_type' => true, + ], + ], + 'php8.2-pseudo-type-true-in-union' => [ + 'identifier' => '/* testPHP82PseudoTypeTrueInUnion */', + 'expected' => [ + 'scope' => 'private', + 'scope_specified' => true, + 'is_static' => false, + 'is_readonly' => false, + 'type' => 'int|string|true', + 'type_token' => -6, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + 'php8.2-pseudo-type-invalid-true-false-union' => [ + 'identifier' => '/* testPHP82PseudoTypeFalseAndTrue */', + 'expected' => [ + 'scope' => 'public', + 'scope_specified' => false, + 'is_static' => false, + 'is_readonly' => true, + 'type' => 'true|FALSE', + 'type_token' => -4, + 'type_end_token' => -2, + 'nullable_type' => false, + ], + ], + + ]; + + }//end dataGetMemberProperties() + + + /** + * Test receiving an expected exception when a non property is passed. + * + * @param string $identifier Comment which precedes the test case. + * + * @dataProvider dataNotClassProperty + * + * @return void + */ + public function testNotClassPropertyException($identifier) + { + $this->expectRunTimeException('$stackPtr is not a class member var'); + + $variable = $this->getTargetToken($identifier, T_VARIABLE); + $result = self::$phpcsFile->getMemberProperties($variable); + + }//end testNotClassPropertyException() + + + /** + * Data provider for the NotClassPropertyException test. + * + * @see testNotClassPropertyException() + * + * @return array> + */ + public function dataNotClassProperty() + { + return [ + 'method parameter' => ['/* testMethodParam */'], + 'variable import using global keyword' => ['/* testImportedGlobal */'], + 'function local variable' => ['/* testLocalVariable */'], + 'global variable' => ['/* testGlobalVariable */'], + 'method parameter in anon class nested in ternary' => ['/* testNestedMethodParam 1 */'], + 'method parameter in anon class nested in function call' => ['/* testNestedMethodParam 2 */'], + 'method parameter in enum' => ['/* testEnumMethodParamNotProperty */'], + ]; + + }//end dataNotClassProperty() + + + /** + * Test receiving an expected exception when a non variable is passed. + * + * @return void + */ + public function testNotAVariableException() + { + $this->expectRunTimeException('$stackPtr must be of type T_VARIABLE'); + + $next = $this->getTargetToken('/* testNotAVariable */', T_RETURN); + $result = self::$phpcsFile->getMemberProperties($next); + + }//end testNotAVariableException() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError1Test.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError1Test.inc new file mode 100644 index 0000000..465679e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError1Test.inc @@ -0,0 +1,4 @@ + + * @copyright 2019-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::getMethodParameters method. + * + * @covers \PHP_CodeSniffer\Files\File::getMethodParameters + */ +class GetMethodParametersParseError1Test extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an empty array when encountering a specific parse error. + * + * @return void + */ + public function testParseError() + { + $target = $this->getTargetToken('/* testParseError */', [T_FUNCTION, T_CLOSURE, T_FN]); + $result = self::$phpcsFile->getMethodParameters($target); + + $this->assertSame([], $result); + + }//end testParseError() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError2Test.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError2Test.inc new file mode 100644 index 0000000..667cb5e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersParseError2Test.inc @@ -0,0 +1,4 @@ + + * @copyright 2019-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::getMethodParameters method. + * + * @covers \PHP_CodeSniffer\Files\File::getMethodParameters + */ +class GetMethodParametersParseError2Test extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an empty array when encountering a specific parse error. + * + * @return void + */ + public function testParseError() + { + $target = $this->getTargetToken('/* testParseError */', [T_FUNCTION, T_CLOSURE, T_FN]); + $result = self::$phpcsFile->getMethodParameters($target); + + $this->assertSame([], $result); + + }//end testParseError() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.inc new file mode 100644 index 0000000..f6f3cd9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.inc @@ -0,0 +1,321 @@ + $b; + +/* testArrowFunctionReturnByRef */ +fn&(?string $a) => $b; + +/* testArrayDefaultValues */ +function arrayDefaultValues($var1 = [], $var2 = array(1, 2, 3) ) {} + +/* testConstantDefaultValueSecondParam */ +function constantDefaultValueSecondParam($var1, $var2 = M_PI) {} + +/* testScalarTernaryExpressionInDefault */ +function ternayInDefault( $a = FOO ? 'bar' : 10, ? bool $b ) {} + +/* testVariadicFunction */ +function variadicFunction( int ... $a ) {} + +/* testVariadicByRefFunction */ +function variadicByRefFunction( &...$a ) {} + +/* testVariadicFunctionClassType */ +function variableLengthArgument($unit, DateInterval ...$intervals) {} + +/* testNameSpacedTypeDeclaration */ +function namespacedClassType( \Package\Sub\ClassName $a, ?Sub\AnotherClass $b ) {} + +/* testWithAllTypes */ +class testAllTypes { + function allTypes( + ?ClassName $a, + self $b, + parent $c, + object $d, + ?int $e, + string &$f, + iterable $g, + bool $h = true, + callable $i = 'is_null', + float $j = 1.1, + array ...$k + ) {} +} + +/* testArrowFunctionWithAllTypes */ +$fn = fn( + ?ClassName $a, + self $b, + parent $c, + object $d, + ?int $e, + string &$f, + iterable $g, + bool $h = true, + callable $i = 'is_null', + float $j = 1.1, + array ...$k +) => $something; + +/* testMessyDeclaration */ +function messyDeclaration( + // comment + ?\MyNS /* comment */ + \ SubCat // phpcs:ignore Standard.Cat.Sniff -- for reasons. + \ MyClass $a, + $b /* test */ = /* test */ 'default' /* test*/, + // phpcs:ignore Stnd.Cat.Sniff -- For reasons. + ? /*comment*/ + bool // phpcs:disable Stnd.Cat.Sniff -- For reasons. + & /*test*/ ... /* phpcs:ignore */ $c +) {} + +/* testPHP8MixedTypeHint */ +function mixedTypeHint(mixed &...$var1) {} + +/* testPHP8MixedTypeHintNullable */ +// Intentional fatal error - nullability is not allowed with mixed, but that's not the concern of the method. +function mixedTypeHintNullable(?Mixed $var1) {} + +/* testNamespaceOperatorTypeHint */ +function namespaceOperatorTypeHint(?namespace\Name $var1) {} + +/* testPHP8UnionTypesSimple */ +function unionTypeSimple(int|float $number, self|parent &...$obj) {} + +/* testPHP8UnionTypesWithSpreadOperatorAndReference */ +function globalFunctionWithSpreadAndReference(float|null &$paramA, string|int ...$paramB ) {} + +/* testPHP8UnionTypesSimpleWithBitwiseOrInDefault */ +$fn = fn(int|float $var = CONSTANT_A | CONSTANT_B) => $var; + +/* testPHP8UnionTypesTwoClasses */ +function unionTypesTwoClasses(MyClassA|\Package\MyClassB $var) {} + +/* testPHP8UnionTypesAllBaseTypes */ +function unionTypesAllBaseTypes(array|bool|callable|int|float|null|object|string $var) {} + +/* testPHP8UnionTypesAllPseudoTypes */ +// Intentional fatal error - mixing types which cannot be combined, but that's not the concern of the method. +function unionTypesAllPseudoTypes(false|mixed|self|parent|iterable|Resource $var) {} + +/* testPHP8UnionTypesNullable */ +// Intentional fatal error - nullability is not allowed with union types, but that's not the concern of the method. +$closure = function (?int|float $number) {}; + +/* testPHP8PseudoTypeNull */ +// PHP 8.0 - 8.1: Intentional fatal error - null pseudotype is only allowed in union types, but that's not the concern of the method. +function pseudoTypeNull(null $var = null) {} + +/* testPHP8PseudoTypeFalse */ +// PHP 8.0 - 8.1: Intentional fatal error - false pseudotype is only allowed in union types, but that's not the concern of the method. +function pseudoTypeFalse(false $var = false) {} + +/* testPHP8PseudoTypeFalseAndBool */ +// Intentional fatal error - false pseudotype is not allowed in combination with bool, but that's not the concern of the method. +function pseudoTypeFalseAndBool(bool|false $var = false) {} + +/* testPHP8ObjectAndClass */ +// Intentional fatal error - object is not allowed in combination with class name, but that's not the concern of the method. +function objectAndClass(object|ClassName $var) {} + +/* testPHP8PseudoTypeIterableAndArray */ +// Intentional fatal error - iterable pseudotype is not allowed in combination with array or Traversable, but that's not the concern of the method. +function pseudoTypeIterableAndArray(iterable|array|Traversable $var) {} + +/* testPHP8DuplicateTypeInUnionWhitespaceAndComment */ +// Intentional fatal error - duplicate types are not allowed in union types, but that's not the concern of the method. +function duplicateTypeInUnion( int | string /*comment*/ | INT $var) {} + +class ConstructorPropertyPromotionNoTypes { + /* testPHP8ConstructorPropertyPromotionNoTypes */ + public function __construct( + public $x = 0.0, + protected $y = '', + private $z = null, + ) {} +} + +class ConstructorPropertyPromotionWithTypes { + /* testPHP8ConstructorPropertyPromotionWithTypes */ + public function __construct(protected float|int $x, public ?string &$y = 'test', private mixed $z) {} +} + +class ConstructorPropertyPromotionAndNormalParams { + /* testPHP8ConstructorPropertyPromotionAndNormalParam */ + public function __construct(public int $promotedProp, ?int $normalArg) {} +} + +class ConstructorPropertyPromotionWithReadOnly { + /* testPHP81ConstructorPropertyPromotionWithReadOnly */ + public function __construct(public readonly ?int $promotedProp, ReadOnly private string|bool &$promotedToo) {} +} + +class ConstructorPropertyPromotionWithReadOnlyNoTypeDeclaration { + /* testPHP81ConstructorPropertyPromotionWithReadOnlyNoTypeDeclaration */ + // Intentional fatal error. Readonly properties MUST be typed. + public function __construct(public readonly $promotedProp, ReadOnly private &$promotedToo) {} +} + +class ConstructorPropertyPromotionWithOnlyReadOnly { + /* testPHP81ConstructorPropertyPromotionWithOnlyReadOnly */ + public function __construct(readonly Foo&Bar $promotedProp, readonly ?bool $promotedToo,) {} +} + +/* testPHP8ConstructorPropertyPromotionGlobalFunction */ +// Intentional fatal error. Property promotion not allowed in non-constructor, but that's not the concern of this method. +function globalFunction(private $x) {} + +abstract class ConstructorPropertyPromotionAbstractMethod { + /* testPHP8ConstructorPropertyPromotionAbstractMethod */ + // Intentional fatal error. + // 1. Property promotion not allowed in abstract method, but that's not the concern of this method. + // 2. Variadic arguments not allowed in property promotion, but that's not the concern of this method. + // 3. The callable type is not supported for properties, but that's not the concern of this method. + abstract public function __construct(public callable $y, private ...$x); +} + +/* testCommentsInParameter */ +function commentsInParams( + // Leading comment. + ?MyClass /*-*/ & /*-*/.../*-*/ $param /*-*/ = /*-*/ 'default value' . /*-*/ 'second part' // Trailing comment. +) {} + +/* testParameterAttributesInFunctionDeclaration */ +class ParametersWithAttributes( + public function __construct( + #[\MyExample\MyAttribute] private string $constructorPropPromTypedParamSingleAttribute, + #[MyAttr([1, 2])] + Type|false + $typedParamSingleAttribute, + #[MyAttribute(1234), MyAttribute(5678)] ?int $nullableTypedParamMultiAttribute, + #[WithoutArgument] #[SingleArgument(0)] $nonTypedParamTwoAttributes, + #[MyAttribute(array("key" => "value"))] + &...$otherParam, + ) {} +} + +/* testPHP8IntersectionTypes */ +function intersectionTypes(Foo&Bar $obj1, Boo&Bar $obj2) {} + +/* testPHP81IntersectionTypesWithSpreadOperatorAndReference */ +function globalFunctionWithSpreadAndReference(Boo&Bar &$paramA, Foo&Bar ...$paramB) {} + +/* testPHP81MoreIntersectionTypes */ +function moreIntersectionTypes(MyClassA&\Package\MyClassB&\Package\MyClassC $var) {} + +/* testPHP81IllegalIntersectionTypes */ +// Intentional fatal error - simple types are not allowed with intersection types, but that's not the concern of the method. +$closure = function (string&int $numeric_string) {}; + +/* testPHP81NullableIntersectionTypes */ +// Intentional fatal error - nullability is not allowed with intersection types, but that's not the concern of the method. +$closure = function (?Foo&Bar $object) {}; + +/* testPHP82PseudoTypeTrue */ +function pseudoTypeTrue(?true $var = true) {} + +/* testPHP82PseudoTypeFalseAndTrue */ +// Intentional fatal error - Type contains both true and false, bool should be used instead, but that's not the concern of the method. +function pseudoTypeFalseAndTrue(true|false $var = true) {} + +/* testPHP81NewInInitializers */ +function newInInitializers( + TypeA $new = new TypeA(self::CONST_VALUE), + \Package\TypeB $newToo = new \Package\TypeB(10, 'string'), +) {} + +/* testFunctionCallFnPHPCS353-354 */ +$value = $obj->fn(true); + +/* testClosureNoParams */ +function() {}; + +/* testClosure */ +function( $a = 'test' ) {}; + +/* testClosureUseNoParams */ +function() use() {}; + +/* testClosureUse */ +function() use( $foo, $bar ) {}; + +/* testFunctionParamListWithTrailingComma */ +function trailingComma( + ?string $foo /*comment*/ , + $bar = 0, +) {} + +/* testClosureParamListWithTrailingComma */ +function( + $foo, + $bar, +) {}; + +/* testArrowFunctionParamListWithTrailingComma */ +$fn = fn( ?int $a , ...$b, ) => $b; + +/* testClosureUseWithTrailingComma */ +function() use( + $foo /*comment*/ , + $bar, +) {}; + +/* testArrowFunctionLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +$fn = fn diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.php new file mode 100644 index 0000000..d0b75a9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodParametersTest.php @@ -0,0 +1,3023 @@ + + * @author Juliette Reinders Folmer + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @copyright 2019-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::getMethodParameters method. + * + * @covers \PHP_CodeSniffer\Files\File::getMethodParameters + */ +class GetMethodParametersTest extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an expected exception when a non function/use token is passed. + * + * @param string $commentString The comment which preceeds the test. + * @param int|string|array $targetTokenType The token type to search for after $commentString. + * + * @dataProvider dataUnexpectedTokenException + * + * @return void + */ + public function testUnexpectedTokenException($commentString, $targetTokenType) + { + $this->expectRunTimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_USE or T_FN'); + + $target = $this->getTargetToken($commentString, $targetTokenType); + self::$phpcsFile->getMethodParameters($target); + + }//end testUnexpectedTokenException() + + + /** + * Data Provider. + * + * @see testUnexpectedTokenException() For the array format. + * + * @return array>> + */ + public static function dataUnexpectedTokenException() + { + return [ + 'interface' => [ + 'commentString' => '/* testNotAFunction */', + 'targetTokenType' => T_INTERFACE, + ], + 'function-call-fn-phpcs-3.5.3-3.5.4' => [ + 'commentString' => '/* testFunctionCallFnPHPCS353-354 */', + 'targetTokenType' => [ + T_FN, + T_STRING, + ], + ], + 'fn-live-coding' => [ + 'commentString' => '/* testArrowFunctionLiveCoding */', + 'targetTokenType' => [ + T_FN, + T_STRING, + ], + ], + ]; + + }//end dataUnexpectedTokenException() + + + /** + * Test receiving an expected exception when a non-closure use token is passed. + * + * @param string $identifier The comment which preceeds the test. + * + * @dataProvider dataInvalidUse + * + * @return void + */ + public function testInvalidUse($identifier) + { + $this->expectRunTimeException('$stackPtr was not a valid T_USE'); + + $use = $this->getTargetToken($identifier, [T_USE]); + self::$phpcsFile->getMethodParameters($use); + + }//end testInvalidUse() + + + /** + * Data Provider. + * + * @see testInvalidUse() For the array format. + * + * @return array> + */ + public static function dataInvalidUse() + { + return [ + 'ImportUse' => ['/* testImportUse */'], + 'ImportGroupUse' => ['/* testImportGroupUse */'], + 'TraitUse' => ['/* testTraitUse */'], + ]; + + }//end dataInvalidUse() + + + /** + * Test receiving an empty array when there are no parameters. + * + * @param string $commentString The comment which preceeds the test. + * @param int|string|array $targetTokenType Optional. The token type to search for after $commentString. + * Defaults to the function/closure/arrow tokens. + * + * @dataProvider dataNoParams + * + * @return void + */ + public function testNoParams($commentString, $targetTokenType=[T_FUNCTION, T_CLOSURE, T_FN]) + { + $target = $this->getTargetToken($commentString, $targetTokenType); + $result = self::$phpcsFile->getMethodParameters($target); + + $this->assertSame([], $result); + + }//end testNoParams() + + + /** + * Data Provider. + * + * @see testNoParams() For the array format. + * + * @return array>> + */ + public static function dataNoParams() + { + return [ + 'FunctionNoParams' => ['/* testFunctionNoParams */'], + 'ClosureNoParams' => ['/* testClosureNoParams */'], + 'ClosureUseNoParams' => [ + '/* testClosureUseNoParams */', + T_USE, + ], + ]; + + }//end dataNoParams() + + + /** + * Verify pass-by-reference parsing. + * + * @return void + */ + public function testPassByReference() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 5, + 'name' => '$var', + 'content' => '&$var', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 4, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPassByReference() + + + /** + * Verify array hint parsing. + * + * @return void + */ + public function testArrayHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var', + 'content' => 'array $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'array', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrayHint() + + + /** + * Verify variable. + * + * @return void + */ + public function testVariable() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$var', + 'content' => '$var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testVariable() + + + /** + * Verify default value parsing with a single function param. + * + * @return void + */ + public function testSingleDefaultValue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$var1', + 'content' => '$var1=self::CONSTANT', + 'default' => 'self::CONSTANT', + 'default_token' => 6, + 'default_equal_token' => 5, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testSingleDefaultValue() + + + /** + * Verify default value parsing. + * + * @return void + */ + public function testDefaultValues() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$var1', + 'content' => '$var1=1', + 'default' => '1', + 'default_token' => 6, + 'default_equal_token' => 5, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 7, + ]; + $expected[1] = [ + 'token' => 9, + 'name' => '$var2', + 'content' => "\$var2='value'", + 'default' => "'value'", + 'default_token' => 11, + 'default_equal_token' => 10, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testDefaultValues() + + + /** + * Verify type hint parsing. + * + * @return void + */ + public function testTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var1', + 'content' => 'foo $var1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'foo', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => 7, + ]; + + $expected[1] = [ + 'token' => 11, + 'name' => '$var2', + 'content' => 'bar $var2', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'bar', + 'type_hint_token' => 9, + 'type_hint_end_token' => 9, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testTypeHint() + + + /** + * Verify self type hint parsing. + * + * @return void + */ + public function testSelfTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var', + 'content' => 'self $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'self', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testSelfTypeHint() + + + /** + * Verify nullable type hint parsing. + * + * @return void + */ + public function testNullableTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$var1', + 'content' => '?int $var1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 5, + 'type_hint_end_token' => 5, + 'nullable_type' => true, + 'comma_token' => 8, + ]; + + $expected[1] = [ + 'token' => 14, + 'name' => '$var2', + 'content' => '?\bar $var2', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?\bar', + 'type_hint_token' => 11, + 'type_hint_end_token' => 12, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNullableTypeHint() + + + /** + * Verify "bitwise and" in default value !== pass-by-reference. + * + * @return void + */ + public function testBitwiseAndConstantExpressionDefaultValue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$a', + 'content' => '$a = 10 & 20', + 'default' => '10 & 20', + 'default_token' => 8, + 'default_equal_token' => 6, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testBitwiseAndConstantExpressionDefaultValue() + + + /** + * Verify that arrow functions are supported. + * + * @return void + */ + public function testArrowFunction() + { + // Offsets are relative to the T_FN token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$a', + 'content' => 'int $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'int', + 'type_hint_token' => 2, + 'type_hint_end_token' => 2, + 'nullable_type' => false, + 'comma_token' => 5, + ]; + + $expected[1] = [ + 'token' => 8, + 'name' => '$b', + 'content' => '...$b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 7, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunction() + + + /** + * Verify that arrow functions are supported. + * + * @return void + */ + public function testArrowFunctionReturnByRef() + { + // Offsets are relative to the T_FN token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$a', + 'content' => '?string $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?string', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunctionReturnByRef() + + + /** + * Verify default value parsing with array values. + * + * @return void + */ + public function testArrayDefaultValues() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$var1', + 'content' => '$var1 = []', + 'default' => '[]', + 'default_token' => 8, + 'default_equal_token' => 6, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 10, + ]; + $expected[1] = [ + 'token' => 12, + 'name' => '$var2', + 'content' => '$var2 = array(1, 2, 3)', + 'default' => 'array(1, 2, 3)', + 'default_token' => 16, + 'default_equal_token' => 14, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrayDefaultValues() + + + /** + * Verify having a T_STRING constant as a default value for the second parameter. + * + * @return void + */ + public function testConstantDefaultValueSecondParam() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$var1', + 'content' => '$var1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 5, + ]; + $expected[1] = [ + 'token' => 7, + 'name' => '$var2', + 'content' => '$var2 = M_PI', + 'default' => 'M_PI', + 'default_token' => 11, + 'default_equal_token' => 9, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testConstantDefaultValueSecondParam() + + + /** + * Verify distinquishing between a nullable type and a ternary within a default expression. + * + * @return void + */ + public function testScalarTernaryExpressionInDefault() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 5, + 'name' => '$a', + 'content' => '$a = FOO ? \'bar\' : 10', + 'default' => 'FOO ? \'bar\' : 10', + 'default_token' => 9, + 'default_equal_token' => 7, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 18, + ]; + $expected[1] = [ + 'token' => 24, + 'name' => '$b', + 'content' => '? bool $b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?bool', + 'type_hint_token' => 22, + 'type_hint_end_token' => 22, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testScalarTernaryExpressionInDefault() + + + /** + * Verify a variadic parameter being recognized correctly. + * + * @return void + */ + public function testVariadicFunction() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$a', + 'content' => 'int ... $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 7, + 'type_hint' => 'int', + 'type_hint_token' => 5, + 'type_hint_end_token' => 5, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testVariadicFunction() + + + /** + * Verify a variadic parameter passed by reference being recognized correctly. + * + * @return void + */ + public function testVariadicByRefFunction() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$a', + 'content' => '&...$a', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 5, + 'variable_length' => true, + 'variadic_token' => 6, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testVariadicByRefFunction() + + + /** + * Verify handling of a variadic parameter with a class based type declaration. + * + * @return void + */ + public function testVariadicFunctionClassType() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$unit', + 'content' => '$unit', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 5, + ]; + $expected[1] = [ + 'token' => 10, + 'name' => '$intervals', + 'content' => 'DateInterval ...$intervals', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 9, + 'type_hint' => 'DateInterval', + 'type_hint_token' => 7, + 'type_hint_end_token' => 7, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testVariadicFunctionClassType() + + + /** + * Verify distinquishing between a nullable type and a ternary within a default expression. + * + * @return void + */ + public function testNameSpacedTypeDeclaration() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 12, + 'name' => '$a', + 'content' => '\Package\Sub\ClassName $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '\Package\Sub\ClassName', + 'type_hint_token' => 5, + 'type_hint_end_token' => 10, + 'nullable_type' => false, + 'comma_token' => 13, + ]; + $expected[1] = [ + 'token' => 20, + 'name' => '$b', + 'content' => '?Sub\AnotherClass $b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?Sub\AnotherClass', + 'type_hint_token' => 16, + 'type_hint_end_token' => 18, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNameSpacedTypeDeclaration() + + + /** + * Verify correctly recognizing all type declarations supported by PHP. + * + * @return void + */ + public function testWithAllTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$a', + 'content' => '?ClassName $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?ClassName', + 'type_hint_token' => 7, + 'type_hint_end_token' => 7, + 'nullable_type' => true, + 'comma_token' => 10, + ]; + $expected[1] = [ + 'token' => 15, + 'name' => '$b', + 'content' => 'self $b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'self', + 'type_hint_token' => 13, + 'type_hint_end_token' => 13, + 'nullable_type' => false, + 'comma_token' => 16, + ]; + $expected[2] = [ + 'token' => 21, + 'name' => '$c', + 'content' => 'parent $c', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'parent', + 'type_hint_token' => 19, + 'type_hint_end_token' => 19, + 'nullable_type' => false, + 'comma_token' => 22, + ]; + $expected[3] = [ + 'token' => 27, + 'name' => '$d', + 'content' => 'object $d', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'object', + 'type_hint_token' => 25, + 'type_hint_end_token' => 25, + 'nullable_type' => false, + 'comma_token' => 28, + ]; + $expected[4] = [ + 'token' => 34, + 'name' => '$e', + 'content' => '?int $e', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 32, + 'type_hint_end_token' => 32, + 'nullable_type' => true, + 'comma_token' => 35, + ]; + $expected[5] = [ + 'token' => 41, + 'name' => '$f', + 'content' => 'string &$f', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 40, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'string', + 'type_hint_token' => 38, + 'type_hint_end_token' => 38, + 'nullable_type' => false, + 'comma_token' => 42, + ]; + $expected[6] = [ + 'token' => 47, + 'name' => '$g', + 'content' => 'iterable $g', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'iterable', + 'type_hint_token' => 45, + 'type_hint_end_token' => 45, + 'nullable_type' => false, + 'comma_token' => 48, + ]; + $expected[7] = [ + 'token' => 53, + 'name' => '$h', + 'content' => 'bool $h = true', + 'default' => 'true', + 'default_token' => 57, + 'default_equal_token' => 55, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'bool', + 'type_hint_token' => 51, + 'type_hint_end_token' => 51, + 'nullable_type' => false, + 'comma_token' => 58, + ]; + $expected[8] = [ + 'token' => 63, + 'name' => '$i', + 'content' => 'callable $i = \'is_null\'', + 'default' => "'is_null'", + 'default_token' => 67, + 'default_equal_token' => 65, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'callable', + 'type_hint_token' => 61, + 'type_hint_end_token' => 61, + 'nullable_type' => false, + 'comma_token' => 68, + ]; + $expected[9] = [ + 'token' => 73, + 'name' => '$j', + 'content' => 'float $j = 1.1', + 'default' => '1.1', + 'default_token' => 77, + 'default_equal_token' => 75, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'float', + 'type_hint_token' => 71, + 'type_hint_end_token' => 71, + 'nullable_type' => false, + 'comma_token' => 78, + ]; + $expected[10] = [ + 'token' => 84, + 'name' => '$k', + 'content' => 'array ...$k', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 83, + 'type_hint' => 'array', + 'type_hint_token' => 81, + 'type_hint_end_token' => 81, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testWithAllTypes() + + + /** + * Verify correctly recognizing all type declarations supported by PHP when used with an arrow function. + * + * @return void + */ + public function testArrowFunctionWithAllTypes() + { + // Offsets are relative to the T_FN token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$a', + 'content' => '?ClassName $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?ClassName', + 'type_hint_token' => 5, + 'type_hint_end_token' => 5, + 'nullable_type' => true, + 'comma_token' => 8, + ]; + $expected[1] = [ + 'token' => 13, + 'name' => '$b', + 'content' => 'self $b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'self', + 'type_hint_token' => 11, + 'type_hint_end_token' => 11, + 'nullable_type' => false, + 'comma_token' => 14, + ]; + $expected[2] = [ + 'token' => 19, + 'name' => '$c', + 'content' => 'parent $c', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'parent', + 'type_hint_token' => 17, + 'type_hint_end_token' => 17, + 'nullable_type' => false, + 'comma_token' => 20, + ]; + $expected[3] = [ + 'token' => 25, + 'name' => '$d', + 'content' => 'object $d', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'object', + 'type_hint_token' => 23, + 'type_hint_end_token' => 23, + 'nullable_type' => false, + 'comma_token' => 26, + ]; + $expected[4] = [ + 'token' => 32, + 'name' => '$e', + 'content' => '?int $e', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 30, + 'type_hint_end_token' => 30, + 'nullable_type' => true, + 'comma_token' => 33, + ]; + $expected[5] = [ + 'token' => 39, + 'name' => '$f', + 'content' => 'string &$f', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 38, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'string', + 'type_hint_token' => 36, + 'type_hint_end_token' => 36, + 'nullable_type' => false, + 'comma_token' => 40, + ]; + $expected[6] = [ + 'token' => 45, + 'name' => '$g', + 'content' => 'iterable $g', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'iterable', + 'type_hint_token' => 43, + 'type_hint_end_token' => 43, + 'nullable_type' => false, + 'comma_token' => 46, + ]; + $expected[7] = [ + 'token' => 51, + 'name' => '$h', + 'content' => 'bool $h = true', + 'default' => 'true', + 'default_token' => 55, + 'default_equal_token' => 53, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'bool', + 'type_hint_token' => 49, + 'type_hint_end_token' => 49, + 'nullable_type' => false, + 'comma_token' => 56, + ]; + $expected[8] = [ + 'token' => 61, + 'name' => '$i', + 'content' => 'callable $i = \'is_null\'', + 'default' => "'is_null'", + 'default_token' => 65, + 'default_equal_token' => 63, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'callable', + 'type_hint_token' => 59, + 'type_hint_end_token' => 59, + 'nullable_type' => false, + 'comma_token' => 66, + ]; + $expected[9] = [ + 'token' => 71, + 'name' => '$j', + 'content' => 'float $j = 1.1', + 'default' => '1.1', + 'default_token' => 75, + 'default_equal_token' => 73, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'float', + 'type_hint_token' => 69, + 'type_hint_end_token' => 69, + 'nullable_type' => false, + 'comma_token' => 76, + ]; + $expected[10] = [ + 'token' => 82, + 'name' => '$k', + 'content' => 'array ...$k', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 81, + 'type_hint' => 'array', + 'type_hint_token' => 79, + 'type_hint_end_token' => 79, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunctionWithAllTypes() + + + /** + * Verify handling of a declaration interlaced with whitespace and comments. + * + * @return void + */ + public function testMessyDeclaration() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 25, + 'name' => '$a', + 'content' => '// comment + ?\MyNS /* comment */ + \ SubCat // phpcs:ignore Standard.Cat.Sniff -- for reasons. + \ MyClass $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?\MyNS\SubCat\MyClass', + 'type_hint_token' => 9, + 'type_hint_end_token' => 23, + 'nullable_type' => true, + 'comma_token' => 26, + ]; + $expected[1] = [ + 'token' => 29, + 'name' => '$b', + 'content' => "\$b /* test */ = /* test */ 'default' /* test*/", + 'default' => "'default' /* test*/", + 'default_token' => 37, + 'default_equal_token' => 33, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 40, + ]; + $expected[2] = [ + 'token' => 62, + 'name' => '$c', + 'content' => '// phpcs:ignore Stnd.Cat.Sniff -- For reasons. + ? /*comment*/ + bool // phpcs:disable Stnd.Cat.Sniff -- For reasons. + & /*test*/ ... /* phpcs:ignore */ $c', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 54, + 'variable_length' => true, + 'variadic_token' => 58, + 'type_hint' => '?bool', + 'type_hint_token' => 50, + 'type_hint_end_token' => 50, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testMessyDeclaration() + + + /** + * Verify recognition of PHP8 mixed type declaration. + * + * @return void + */ + public function testPHP8MixedTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$var1', + 'content' => 'mixed &...$var1', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 6, + 'variable_length' => true, + 'variadic_token' => 7, + 'type_hint' => 'mixed', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8MixedTypeHint() + + + /** + * Verify recognition of PHP8 mixed type declaration with nullability. + * + * @return void + */ + public function testPHP8MixedTypeHintNullable() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$var1', + 'content' => '?Mixed $var1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?Mixed', + 'type_hint_token' => 5, + 'type_hint_end_token' => 5, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8MixedTypeHintNullable() + + + /** + * Verify recognition of type declarations using the namespace operator. + * + * @return void + */ + public function testNamespaceOperatorTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$var1', + 'content' => '?namespace\Name $var1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?namespace\Name', + 'type_hint_token' => 5, + 'type_hint_end_token' => 7, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNamespaceOperatorTypeHint() + + + /** + * Verify recognition of PHP8 union type declaration. + * + * @return void + */ + public function testPHP8UnionTypesSimple() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$number', + 'content' => 'int|float $number', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'int|float', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => 9, + ]; + $expected[1] = [ + 'token' => 17, + 'name' => '$obj', + 'content' => 'self|parent &...$obj', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 15, + 'variable_length' => true, + 'variadic_token' => 16, + 'type_hint' => 'self|parent', + 'type_hint_token' => 11, + 'type_hint_end_token' => 13, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesSimple() + + + /** + * Verify recognition of PHP8 union type declaration when the variable has either a spread operator or a reference. + * + * @return void + */ + public function testPHP8UnionTypesWithSpreadOperatorAndReference() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$paramA', + 'content' => 'float|null &$paramA', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 8, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'float|null', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => 10, + ]; + $expected[1] = [ + 'token' => 17, + 'name' => '$paramB', + 'content' => 'string|int ...$paramB', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 16, + 'type_hint' => 'string|int', + 'type_hint_token' => 12, + 'type_hint_end_token' => 14, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesWithSpreadOperatorAndReference() + + + /** + * Verify recognition of PHP8 union type declaration with a bitwise or in the default value. + * + * @return void + */ + public function testPHP8UnionTypesSimpleWithBitwiseOrInDefault() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var', + 'content' => 'int|float $var = CONSTANT_A | CONSTANT_B', + 'default' => 'CONSTANT_A | CONSTANT_B', + 'default_token' => 10, + 'default_equal_token' => 8, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'int|float', + 'type_hint_token' => 2, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesSimpleWithBitwiseOrInDefault() + + + /** + * Verify recognition of PHP8 union type declaration with two classes. + * + * @return void + */ + public function testPHP8UnionTypesTwoClasses() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 11, + 'name' => '$var', + 'content' => 'MyClassA|\Package\MyClassB $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'MyClassA|\Package\MyClassB', + 'type_hint_token' => 4, + 'type_hint_end_token' => 9, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesTwoClasses() + + + /** + * Verify recognition of PHP8 union type declaration with all base types. + * + * @return void + */ + public function testPHP8UnionTypesAllBaseTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 20, + 'name' => '$var', + 'content' => 'array|bool|callable|int|float|null|object|string $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'array|bool|callable|int|float|null|object|string', + 'type_hint_token' => 4, + 'type_hint_end_token' => 18, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesAllBaseTypes() + + + /** + * Verify recognition of PHP8 union type declaration with all pseudo types. + * + * Note: "Resource" is not a type, but seen as a class name. + * + * @return void + */ + public function testPHP8UnionTypesAllPseudoTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 16, + 'name' => '$var', + 'content' => 'false|mixed|self|parent|iterable|Resource $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'false|mixed|self|parent|iterable|Resource', + 'type_hint_token' => 4, + 'type_hint_end_token' => 14, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesAllPseudoTypes() + + + /** + * Verify recognition of PHP8 union type declaration with (illegal) nullability. + * + * @return void + */ + public function testPHP8UnionTypesNullable() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$number', + 'content' => '?int|float $number', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int|float', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesNullable() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) single type null. + * + * @return void + */ + public function testPHP8PseudoTypeNull() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var', + 'content' => 'null $var = null', + 'default' => 'null', + 'default_token' => 10, + 'default_equal_token' => 8, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'null', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeNull() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) single type false. + * + * @return void + */ + public function testPHP8PseudoTypeFalse() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$var', + 'content' => 'false $var = false', + 'default' => 'false', + 'default_token' => 10, + 'default_equal_token' => 8, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'false', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeFalse() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type false combined with type bool. + * + * @return void + */ + public function testPHP8PseudoTypeFalseAndBool() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$var', + 'content' => 'bool|false $var = false', + 'default' => 'false', + 'default_token' => 12, + 'default_equal_token' => 10, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'bool|false', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeFalseAndBool() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type object combined with a class name. + * + * @return void + */ + public function testPHP8ObjectAndClass() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$var', + 'content' => 'object|ClassName $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'object|ClassName', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ObjectAndClass() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type iterable combined with array/Traversable. + * + * @return void + */ + public function testPHP8PseudoTypeIterableAndArray() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 10, + 'name' => '$var', + 'content' => 'iterable|array|Traversable $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'iterable|array|Traversable', + 'type_hint_token' => 4, + 'type_hint_end_token' => 8, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeIterableAndArray() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) duplicate types. + * + * @return void + */ + public function testPHP8DuplicateTypeInUnionWhitespaceAndComment() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 17, + 'name' => '$var', + 'content' => 'int | string /*comment*/ | INT $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'int|string|INT', + 'type_hint_token' => 5, + 'type_hint_end_token' => 15, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8DuplicateTypeInUnionWhitespaceAndComment() + + + /** + * Verify recognition of PHP8 constructor property promotion without type declaration, with defaults. + * + * @return void + */ + public function testPHP8ConstructorPropertyPromotionNoTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$x', + 'content' => 'public $x = 0.0', + 'default' => '0.0', + 'default_token' => 12, + 'default_equal_token' => 10, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'public', + 'visibility_token' => 6, + 'property_readonly' => false, + 'comma_token' => 13, + ]; + $expected[1] = [ + 'token' => 18, + 'name' => '$y', + 'content' => 'protected $y = \'\'', + 'default' => "''", + 'default_token' => 22, + 'default_equal_token' => 20, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'protected', + 'visibility_token' => 16, + 'property_readonly' => false, + 'comma_token' => 23, + ]; + $expected[2] = [ + 'token' => 28, + 'name' => '$z', + 'content' => 'private $z = null', + 'default' => 'null', + 'default_token' => 32, + 'default_equal_token' => 30, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 26, + 'property_readonly' => false, + 'comma_token' => 33, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ConstructorPropertyPromotionNoTypes() + + + /** + * Verify recognition of PHP8 constructor property promotion with type declarations. + * + * @return void + */ + public function testPHP8ConstructorPropertyPromotionWithTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 10, + 'name' => '$x', + 'content' => 'protected float|int $x', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'float|int', + 'type_hint_token' => 6, + 'type_hint_end_token' => 8, + 'nullable_type' => false, + 'property_visibility' => 'protected', + 'visibility_token' => 4, + 'property_readonly' => false, + 'comma_token' => 11, + ]; + $expected[1] = [ + 'token' => 19, + 'name' => '$y', + 'content' => 'public ?string &$y = \'test\'', + 'default' => "'test'", + 'default_token' => 23, + 'default_equal_token' => 21, + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 18, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?string', + 'type_hint_token' => 16, + 'type_hint_end_token' => 16, + 'nullable_type' => true, + 'property_visibility' => 'public', + 'visibility_token' => 13, + 'property_readonly' => false, + 'comma_token' => 24, + ]; + $expected[2] = [ + 'token' => 30, + 'name' => '$z', + 'content' => 'private mixed $z', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'mixed', + 'type_hint_token' => 28, + 'type_hint_end_token' => 28, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 26, + 'property_readonly' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ConstructorPropertyPromotionWithTypes() + + + /** + * Verify recognition of PHP8 constructor with both property promotion as well as normal parameters. + * + * @return void + */ + public function testPHP8ConstructorPropertyPromotionAndNormalParam() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$promotedProp', + 'content' => 'public int $promotedProp', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'int', + 'type_hint_token' => 6, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'property_visibility' => 'public', + 'visibility_token' => 4, + 'property_readonly' => false, + 'comma_token' => 9, + ]; + $expected[1] = [ + 'token' => 14, + 'name' => '$normalArg', + 'content' => '?int $normalArg', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 12, + 'type_hint_end_token' => 12, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ConstructorPropertyPromotionAndNormalParam() + + + /** + * Verify recognition of PHP8 constructor with property promotion using PHP 8.1 readonly keyword. + * + * @return void + */ + public function testPHP81ConstructorPropertyPromotionWithReadOnly() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 11, + 'name' => '$promotedProp', + 'content' => 'public readonly ?int $promotedProp', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 9, + 'type_hint_end_token' => 9, + 'nullable_type' => true, + 'property_visibility' => 'public', + 'visibility_token' => 4, + 'property_readonly' => true, + 'readonly_token' => 6, + 'comma_token' => 12, + ]; + $expected[1] = [ + 'token' => 23, + 'name' => '$promotedToo', + 'content' => 'ReadOnly private string|bool &$promotedToo', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 22, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'string|bool', + 'type_hint_token' => 18, + 'type_hint_end_token' => 20, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 16, + 'property_readonly' => true, + 'readonly_token' => 14, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81ConstructorPropertyPromotionWithReadOnly() + + + /** + * Verify recognition of PHP8 constructor with property promotion using PHP 8.1 readonly keyword + * without a property type. + * + * @return void + */ + public function testPHP81ConstructorPropertyPromotionWithReadOnlyNoTypeDeclaration() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$promotedProp', + 'content' => 'public readonly $promotedProp', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'public', + 'visibility_token' => 4, + 'property_readonly' => true, + 'readonly_token' => 6, + 'comma_token' => 9, + ]; + $expected[1] = [ + 'token' => 16, + 'name' => '$promotedToo', + 'content' => 'ReadOnly private &$promotedToo', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 15, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 13, + 'property_readonly' => true, + 'readonly_token' => 11, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81ConstructorPropertyPromotionWithReadOnlyNoTypeDeclaration() + + + /** + * Verify recognition of PHP8 constructor with property promotion using PHP 8.1 readonly + * keyword without explicit visibility. + * + * @return void + */ + public function testPHP81ConstructorPropertyPromotionWithOnlyReadOnly() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 10, + 'name' => '$promotedProp', + 'content' => 'readonly Foo&Bar $promotedProp', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'Foo&Bar', + 'type_hint_token' => 6, + 'type_hint_end_token' => 8, + 'nullable_type' => false, + 'property_visibility' => 'public', + 'visibility_token' => false, + 'property_readonly' => true, + 'readonly_token' => 4, + 'comma_token' => 11, + ]; + $expected[1] = [ + 'token' => 18, + 'name' => '$promotedToo', + 'content' => 'readonly ?bool $promotedToo', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?bool', + 'type_hint_token' => 16, + 'type_hint_end_token' => 16, + 'nullable_type' => true, + 'property_visibility' => 'public', + 'visibility_token' => false, + 'property_readonly' => true, + 'readonly_token' => 13, + 'comma_token' => 19, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81ConstructorPropertyPromotionWithOnlyReadOnly() + + + /** + * Verify behaviour when a non-constructor function uses PHP 8 property promotion syntax. + * + * @return void + */ + public function testPHP8ConstructorPropertyPromotionGlobalFunction() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$x', + 'content' => 'private $x', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 4, + 'property_readonly' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ConstructorPropertyPromotionGlobalFunction() + + + /** + * Verify behaviour when an abstract constructor uses PHP 8 property promotion syntax. + * + * @return void + */ + public function testPHP8ConstructorPropertyPromotionAbstractMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$y', + 'content' => 'public callable $y', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'callable', + 'type_hint_token' => 6, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'property_visibility' => 'public', + 'visibility_token' => 4, + 'property_readonly' => false, + 'comma_token' => 9, + ]; + $expected[1] = [ + 'token' => 14, + 'name' => '$x', + 'content' => 'private ...$x', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 13, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 11, + 'property_readonly' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ConstructorPropertyPromotionAbstractMethod() + + + /** + * Verify and document behaviour when there are comments within a parameter declaration. + * + * @return void + */ + public function testCommentsInParameter() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 19, + 'name' => '$param', + 'content' => '// Leading comment. + ?MyClass /*-*/ & /*-*/.../*-*/ $param /*-*/ = /*-*/ \'default value\' . /*-*/ \'second part\' // Trailing comment.', + 'default' => '\'default value\' . /*-*/ \'second part\' // Trailing comment.', + 'default_token' => 27, + 'default_equal_token' => 23, + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 13, + 'variable_length' => true, + 'variadic_token' => 16, + 'type_hint' => '?MyClass', + 'type_hint_token' => 9, + 'type_hint_end_token' => 9, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testCommentsInParameter() + + + /** + * Verify behaviour when parameters have attributes attached. + * + * @return void + */ + public function testParameterAttributesInFunctionDeclaration() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 17, + 'name' => '$constructorPropPromTypedParamSingleAttribute', + 'content' => '#[\MyExample\MyAttribute] private string $constructorPropPromTypedParamSingleAttribute', + 'has_attributes' => true, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'string', + 'type_hint_token' => 15, + 'type_hint_end_token' => 15, + 'nullable_type' => false, + 'property_visibility' => 'private', + 'visibility_token' => 13, + 'property_readonly' => false, + 'comma_token' => 18, + ]; + $expected[1] = [ + 'token' => 39, + 'name' => '$typedParamSingleAttribute', + 'content' => '#[MyAttr([1, 2])] + Type|false + $typedParamSingleAttribute', + 'has_attributes' => true, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'Type|false', + 'type_hint_token' => 34, + 'type_hint_end_token' => 36, + 'nullable_type' => false, + 'comma_token' => 40, + ]; + $expected[2] = [ + 'token' => 59, + 'name' => '$nullableTypedParamMultiAttribute', + 'content' => '#[MyAttribute(1234), MyAttribute(5678)] ?int $nullableTypedParamMultiAttribute', + 'has_attributes' => true, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 57, + 'type_hint_end_token' => 57, + 'nullable_type' => true, + 'comma_token' => 60, + ]; + $expected[3] = [ + 'token' => 74, + 'name' => '$nonTypedParamTwoAttributes', + 'content' => '#[WithoutArgument] #[SingleArgument(0)] $nonTypedParamTwoAttributes', + 'has_attributes' => true, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 75, + ]; + $expected[4] = [ + 'token' => 95, + 'name' => '$otherParam', + 'content' => '#[MyAttribute(array("key" => "value"))] + &...$otherParam', + 'has_attributes' => true, + 'pass_by_reference' => true, + 'reference_token' => 93, + 'variable_length' => true, + 'variadic_token' => 94, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 96, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testParameterAttributesInFunctionDeclaration() + + + /** + * Verify recognition of PHP8.1 intersection type declaration. + * + * @return void + */ + public function testPHP8IntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$obj1', + 'content' => 'Foo&Bar $obj1', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'Foo&Bar', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => 9, + ]; + $expected[1] = [ + 'token' => 15, + 'name' => '$obj2', + 'content' => 'Boo&Bar $obj2', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'Boo&Bar', + 'type_hint_token' => 11, + 'type_hint_end_token' => 13, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8IntersectionTypes() + + + /** + * Verify recognition of PHP8 intersection type declaration when the variable + * has either a spread operator or a reference. + * + * @return void + */ + public function testPHP81IntersectionTypesWithSpreadOperatorAndReference() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$paramA', + 'content' => 'Boo&Bar &$paramA', + 'has_attributes' => false, + 'pass_by_reference' => true, + 'reference_token' => 8, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'Boo&Bar', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => 10, + ]; + $expected[1] = [ + 'token' => 17, + 'name' => '$paramB', + 'content' => 'Foo&Bar ...$paramB', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 16, + 'type_hint' => 'Foo&Bar', + 'type_hint_token' => 12, + 'type_hint_end_token' => 14, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81IntersectionTypesWithSpreadOperatorAndReference() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with more types. + * + * @return void + */ + public function testPHP81MoreIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 16, + 'name' => '$var', + 'content' => 'MyClassA&\Package\MyClassB&\Package\MyClassC $var', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'MyClassA&\Package\MyClassB&\Package\MyClassC', + 'type_hint_token' => 4, + 'type_hint_end_token' => 14, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81MoreIntersectionTypes() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with illegal simple types. + * + * @return void + */ + public function testPHP81IllegalIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$numeric_string', + 'content' => 'string&int $numeric_string', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'string&int', + 'type_hint_token' => 3, + 'type_hint_end_token' => 5, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81IllegalIntersectionTypes() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with (illegal) nullability. + * + * @return void + */ + public function testPHP81NullableIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$object', + 'content' => '?Foo&Bar $object', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?Foo&Bar', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81NullableIntersectionTypes() + + + /** + * Verify recognition of PHP 8.2 stand-alone `true` type. + * + * @return void + */ + public function testPHP82PseudoTypeTrue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 7, + 'name' => '$var', + 'content' => '?true $var = true', + 'default' => 'true', + 'default_token' => 11, + 'default_equal_token' => 9, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?true', + 'type_hint_token' => 5, + 'type_hint_end_token' => 5, + 'nullable_type' => true, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP82PseudoTypeTrue() + + + /** + * Verify recognition of PHP 8.2 type declaration with (illegal) type false combined with type true. + * + * @return void + */ + public function testPHP82PseudoTypeFalseAndTrue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$var', + 'content' => 'true|false $var = true', + 'default' => 'true', + 'default_token' => 12, + 'default_equal_token' => 10, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'true|false', + 'type_hint_token' => 4, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP82PseudoTypeFalseAndTrue() + + + /** + * Verify behaviour when the default value uses the "new" keyword, as is allowed per PHP 8.1. + * + * @return void + */ + public function testPHP81NewInInitializers() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 8, + 'name' => '$new', + 'content' => 'TypeA $new = new TypeA(self::CONST_VALUE)', + 'default' => 'new TypeA(self::CONST_VALUE)', + 'default_token' => 12, + 'default_equal_token' => 10, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => 'TypeA', + 'type_hint_token' => 6, + 'type_hint_end_token' => 6, + 'nullable_type' => false, + 'comma_token' => 20, + ]; + $expected[1] = [ + 'token' => 28, + 'name' => '$newToo', + 'content' => '\Package\TypeB $newToo = new \Package\TypeB(10, \'string\')', + 'default' => "new \Package\TypeB(10, 'string')", + 'default_token' => 32, + 'default_equal_token' => 30, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '\Package\TypeB', + 'type_hint_token' => 23, + 'type_hint_end_token' => 26, + 'nullable_type' => false, + 'comma_token' => 44, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81NewInInitializers() + + + /** + * Verify handling of a closure. + * + * @return void + */ + public function testClosure() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 3, + 'name' => '$a', + 'content' => '$a = \'test\'', + 'default' => "'test'", + 'default_token' => 7, + 'default_equal_token' => 5, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testClosure() + + + /** + * Verify handling of a closure T_USE token correctly. + * + * @return void + */ + public function testClosureUse() + { + // Offsets are relative to the T_USE token. + $expected = []; + $expected[0] = [ + 'token' => 3, + 'name' => '$foo', + 'content' => '$foo', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 4, + ]; + $expected[1] = [ + 'token' => 6, + 'name' => '$bar', + 'content' => '$bar', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => false, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected, [T_USE]); + + }//end testClosureUse() + + + /** + * Verify function declarations with trailing commas are handled correctly. + * + * @return void + */ + public function testFunctionParamListWithTrailingComma() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 9, + 'name' => '$foo', + 'content' => '?string $foo /*comment*/', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?string', + 'type_hint_token' => 7, + 'type_hint_end_token' => 7, + 'nullable_type' => true, + 'comma_token' => 13, + ]; + $expected[1] = [ + 'token' => 16, + 'name' => '$bar', + 'content' => '$bar = 0', + 'default' => '0', + 'default_token' => 20, + 'default_equal_token' => 18, + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 21, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testFunctionParamListWithTrailingComma() + + + /** + * Verify closure declarations with trailing commas are handled correctly. + * + * @return void + */ + public function testClosureParamListWithTrailingComma() + { + // Offsets are relative to the T_FUNCTION token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$foo', + 'content' => '$foo', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 5, + ]; + $expected[1] = [ + 'token' => 8, + 'name' => '$bar', + 'content' => '$bar', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 9, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testClosureParamListWithTrailingComma() + + + /** + * Verify arrow function declarations with trailing commas are handled correctly. + * + * @return void + */ + public function testArrowFunctionParamListWithTrailingComma() + { + // Offsets are relative to the T_FN token. + $expected = []; + $expected[0] = [ + 'token' => 6, + 'name' => '$a', + 'content' => '?int $a', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '?int', + 'type_hint_token' => 4, + 'type_hint_end_token' => 4, + 'nullable_type' => true, + 'comma_token' => 8, + ]; + $expected[1] = [ + 'token' => 11, + 'name' => '$b', + 'content' => '...$b', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => true, + 'variadic_token' => 10, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 12, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunctionParamListWithTrailingComma() + + + /** + * Verify closure T_USE statements with trailing commas are handled correctly. + * + * @return void + */ + public function testClosureUseWithTrailingComma() + { + // Offsets are relative to the T_USE token. + $expected = []; + $expected[0] = [ + 'token' => 4, + 'name' => '$foo', + 'content' => '$foo /*comment*/', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 8, + ]; + $expected[1] = [ + 'token' => 11, + 'name' => '$bar', + 'content' => '$bar', + 'has_attributes' => false, + 'pass_by_reference' => false, + 'reference_token' => false, + 'variable_length' => false, + 'variadic_token' => false, + 'type_hint' => '', + 'type_hint_token' => false, + 'type_hint_end_token' => false, + 'nullable_type' => false, + 'comma_token' => 12, + ]; + + $this->getMethodParametersTestHelper('/* '.__FUNCTION__.' */', $expected, [T_USE]); + + }//end testClosureUseWithTrailingComma() + + + /** + * Test helper. + * + * @param string $commentString The comment which preceeds the test. + * @param array> $expected The expected function output. + * @param int|string|array $targetType Optional. The token type to search for after $marker. + * Defaults to the function/closure/arrow tokens. + * + * @return void + */ + private function getMethodParametersTestHelper($commentString, $expected, $targetType=[T_FUNCTION, T_CLOSURE, T_FN]) + { + $target = $this->getTargetToken($commentString, $targetType); + $found = self::$phpcsFile->getMethodParameters($target); + + // Convert offsets to absolute positions in the token stream. + foreach ($expected as $key => $param) { + $expected[$key]['token'] += $target; + + if (is_int($param['reference_token']) === true) { + $expected[$key]['reference_token'] += $target; + } + + if (is_int($param['variadic_token']) === true) { + $expected[$key]['variadic_token'] += $target; + } + + if (is_int($param['type_hint_token']) === true) { + $expected[$key]['type_hint_token'] += $target; + } + + if (is_int($param['type_hint_end_token']) === true) { + $expected[$key]['type_hint_end_token'] += $target; + } + + if (is_int($param['comma_token']) === true) { + $expected[$key]['comma_token'] += $target; + } + + if (isset($param['default_token']) === true) { + $expected[$key]['default_token'] += $target; + } + + if (isset($param['default_equal_token']) === true) { + $expected[$key]['default_equal_token'] += $target; + } + + if (isset($param['visibility_token']) === true && is_int($param['visibility_token']) === true) { + $expected[$key]['visibility_token'] += $target; + } + + if (isset($param['readonly_token']) === true) { + $expected[$key]['readonly_token'] += $target; + } + }//end foreach + + $this->assertSame($expected, $found); + + }//end getMethodParametersTestHelper() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.inc new file mode 100644 index 0000000..1bc5705 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.inc @@ -0,0 +1,190 @@ + $number + 1, + $numbers +); + +class ReturnMe { + /* testReturnTypeStatic */ + private function myFunction(): static { + return $this; + } +} + +/* testPHP8MixedTypeHint */ +function mixedTypeHint() :mixed {} + +/* testPHP8MixedTypeHintNullable */ +// Intentional fatal error - nullability is not allowed with mixed, but that's not the concern of the method. +function mixedTypeHintNullable(): ?mixed {} + +/* testNamespaceOperatorTypeHint */ +function namespaceOperatorTypeHint() : ?namespace\Name {} + +/* testPHP8UnionTypesSimple */ +function unionTypeSimple($number) : int|float {} + +/* testPHP8UnionTypesTwoClasses */ +$fn = fn($var): MyClassA|\Package\MyClassB => $var; + +/* testPHP8UnionTypesAllBaseTypes */ +function unionTypesAllBaseTypes() : array|bool|callable|int|float|null|Object|string {} + +/* testPHP8UnionTypesAllPseudoTypes */ +// Intentional fatal error - mixing types which cannot be combined, but that's not the concern of the method. +function unionTypesAllPseudoTypes($var) : false|MIXED|self|parent|static|iterable|Resource|void {} + +/* testPHP8UnionTypesNullable */ +// Intentional fatal error - nullability is not allowed with union types, but that's not the concern of the method. +$closure = function () use($a) :?int|float {}; + +/* testPHP8PseudoTypeNull */ +// PHP 8.0 - 8.1: Intentional fatal error - null pseudotype is only allowed in union types, but that's not the concern of the method. +function pseudoTypeNull(): null {} + +/* testPHP8PseudoTypeFalse */ +// PHP 8.0 - 8.1: Intentional fatal error - false pseudotype is only allowed in union types, but that's not the concern of the method. +function pseudoTypeFalse(): false {} + +/* testPHP8PseudoTypeFalseAndBool */ +// Intentional fatal error - false pseudotype is not allowed in combination with bool, but that's not the concern of the method. +function pseudoTypeFalseAndBool(): bool|false {} + +/* testPHP8ObjectAndClass */ +// Intentional fatal error - object is not allowed in combination with class name, but that's not the concern of the method. +function objectAndClass(): object|ClassName {} + +/* testPHP8PseudoTypeIterableAndArray */ +// Intentional fatal error - iterable pseudotype is not allowed in combination with array or Traversable, but that's not the concern of the method. +interface FooBar { + public function pseudoTypeIterableAndArray(): iterable|array|Traversable; +} + +/* testPHP8DuplicateTypeInUnionWhitespaceAndComment */ +// Intentional fatal error - duplicate types are not allowed in union types, but that's not the concern of the method. +function duplicateTypeInUnion(): int | /*comment*/ string | INT {} + +/* testPHP81NeverType */ +function never(): never {} + +/* testPHP81NullableNeverType */ +// Intentional fatal error - nullability is not allowed with never, but that's not the concern of the method. +function nullableNever(): ?never {} + +/* testPHP8IntersectionTypes */ +function intersectionTypes(): Foo&Bar {} + +/* testPHP81MoreIntersectionTypes */ +function moreIntersectionTypes(): MyClassA&\Package\MyClassB&\Package\MyClassC {} + +/* testPHP81IntersectionArrowFunction */ +$fn = fn($var): MyClassA&\Package\MyClassB => $var; + +/* testPHP81IllegalIntersectionTypes */ +// Intentional fatal error - simple types are not allowed with intersection types, but that's not the concern of the method. +$closure = function (): string&int {}; + +/* testPHP81NullableIntersectionTypes */ +// Intentional fatal error - nullability is not allowed with intersection types, but that's not the concern of the method. +$closure = function (): ?Foo&Bar {}; + +/* testPHP82PseudoTypeTrue */ +function pseudoTypeTrue(): ?true {} + +/* testPHP82PseudoTypeFalseAndTrue */ +// Intentional fatal error - Type contains both true and false, bool should be used instead, but that's not the concern of the method. +function pseudoTypeFalseAndTrue(): true|false {} + +/* testNotAFunction */ +return true; + +/* testPhpcsIssue1264 */ +function foo() : array { + echo $foo; +} + +/* testArrowFunctionArrayReturnValue */ +$fn = fn(): array => [a($a, $b)]; + +/* testArrowFunctionReturnByRef */ +fn&(?string $a) : ?string => $b; + +/* testFunctionCallFnPHPCS353-354 */ +$value = $obj->fn(true); + +/* testFunctionDeclarationNestedInTernaryPHPCS2975 */ +return (!$a ? [ new class { public function b(): c {} } ] : []); + +/* testArrowFunctionLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +$fn = fn diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.php new file mode 100644 index 0000000..b7c8bc9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetMethodPropertiesTest.php @@ -0,0 +1,1301 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::getMethodProperties method. + * + * @covers \PHP_CodeSniffer\Files\File::getMethodProperties + */ +class GetMethodPropertiesTest extends AbstractMethodUnitTest +{ + + + /** + * Test receiving an expected exception when a non function token is passed. + * + * @param string $commentString The comment which preceeds the test. + * @param string|int|array $targetTokenType The token type to search for after $commentString. + * + * @dataProvider dataNotAFunctionException + * + * @return void + */ + public function testNotAFunctionException($commentString, $targetTokenType) + { + $this->expectRunTimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_FN'); + + $next = $this->getTargetToken($commentString, $targetTokenType); + self::$phpcsFile->getMethodProperties($next); + + }//end testNotAFunctionException() + + + /** + * Data Provider. + * + * @see testNotAFunctionException() For the array format. + * + * @return array>> + */ + public static function dataNotAFunctionException() + { + return [ + 'return' => [ + 'commentString' => '/* testNotAFunction */', + 'targetTokenType' => T_RETURN, + ], + 'function-call-fn-phpcs-3.5.3-3.5.4' => [ + 'commentString' => '/* testFunctionCallFnPHPCS353-354 */', + 'targetTokenType' => [ + T_FN, + T_STRING, + ], + ], + 'fn-live-coding' => [ + 'commentString' => '/* testArrowFunctionLiveCoding */', + 'targetTokenType' => [ + T_FN, + T_STRING, + ], + ], + ]; + + }//end dataNotAFunctionException() + + + /** + * Test a basic function. + * + * @return void + */ + public function testBasicFunction() + { + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testBasicFunction() + + + /** + * Test a function with a return type. + * + * @return void + */ + public function testReturnFunction() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'array', + 'return_type_token' => 11, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnFunction() + + + /** + * Test a closure used as a function argument. + * + * @return void + */ + public function testNestedClosure() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'int', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNestedClosure() + + + /** + * Test a basic method. + * + * @return void + */ + public function testBasicMethod() + { + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testBasicMethod() + + + /** + * Test a private static method. + * + * @return void + */ + public function testPrivateStaticMethod() + { + $expected = [ + 'scope' => 'private', + 'scope_specified' => true, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => true, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPrivateStaticMethod() + + + /** + * Test a basic final method. + * + * @return void + */ + public function testFinalMethod() + { + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => true, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testFinalMethod() + + + /** + * Test a protected method with a return type. + * + * @return void + */ + public function testProtectedReturnMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'protected', + 'scope_specified' => true, + 'return_type' => 'int', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testProtectedReturnMethod() + + + /** + * Test a public method with a return type. + * + * @return void + */ + public function testPublicReturnMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => 'array', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPublicReturnMethod() + + + /** + * Test a public method with a nullable return type. + * + * @return void + */ + public function testNullableReturnMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => '?array', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNullableReturnMethod() + + + /** + * Test a public method with a nullable return type. + * + * @return void + */ + public function testMessyNullableReturnMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => '?array', + 'return_type_token' => 18, + 'return_type_end_token' => 18, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testMessyNullableReturnMethod() + + + /** + * Test a method with a namespaced return type. + * + * @return void + */ + public function testReturnNamespace() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '\MyNamespace\MyClass', + 'return_type_token' => 7, + 'return_type_end_token' => 10, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnNamespace() + + + /** + * Test a method with a messy namespaces return type. + * + * @return void + */ + public function testReturnMultilineNamespace() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '\MyNamespace\MyClass\Foo', + 'return_type_token' => 7, + 'return_type_end_token' => 23, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnMultilineNamespace() + + + /** + * Test a method with an unqualified named return type. + * + * @return void + */ + public function testReturnUnqualifiedName() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'private', + 'scope_specified' => true, + 'return_type' => '?MyClass', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnUnqualifiedName() + + + /** + * Test a method with a partially qualified namespaced return type. + * + * @return void + */ + public function testReturnPartiallyQualifiedName() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'Sub\Level\MyClass', + 'return_type_token' => 7, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnPartiallyQualifiedName() + + + /** + * Test a basic abstract method. + * + * @return void + */ + public function testAbstractMethod() + { + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => true, + 'is_final' => false, + 'is_static' => false, + 'has_body' => false, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testAbstractMethod() + + + /** + * Test an abstract method with a return type. + * + * @return void + */ + public function testAbstractReturnMethod() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'protected', + 'scope_specified' => true, + 'return_type' => 'bool', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => true, + 'is_final' => false, + 'is_static' => false, + 'has_body' => false, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testAbstractReturnMethod() + + + /** + * Test a basic interface method. + * + * @return void + */ + public function testInterfaceMethod() + { + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '', + 'return_type_token' => false, + 'return_type_end_token' => false, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => false, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testInterfaceMethod() + + + /** + * Test a static arrow function. + * + * @return void + */ + public function testArrowFunction() + { + // Offsets are relative to the T_FN token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'int', + 'return_type_token' => 9, + 'return_type_end_token' => 9, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => true, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunction() + + + /** + * Test a function with return type "static". + * + * @return void + */ + public function testReturnTypeStatic() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'private', + 'scope_specified' => true, + 'return_type' => 'static', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testReturnTypeStatic() + + + /** + * Test a function with return type "mixed". + * + * @return void + */ + public function testPHP8MixedTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'mixed', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8MixedTypeHint() + + + /** + * Test a function with return type "mixed" and nullability. + * + * @return void + */ + public function testPHP8MixedTypeHintNullable() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?mixed', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8MixedTypeHintNullable() + + + /** + * Test a function with return type using the namespace operator. + * + * @return void + */ + public function testNamespaceOperatorTypeHint() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?namespace\Name', + 'return_type_token' => 9, + 'return_type_end_token' => 11, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testNamespaceOperatorTypeHint() + + + /** + * Verify recognition of PHP8 union type declaration. + * + * @return void + */ + public function testPHP8UnionTypesSimple() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'int|float', + 'return_type_token' => 9, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesSimple() + + + /** + * Verify recognition of PHP8 union type declaration with two classes. + * + * @return void + */ + public function testPHP8UnionTypesTwoClasses() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'MyClassA|\Package\MyClassB', + 'return_type_token' => 6, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesTwoClasses() + + + /** + * Verify recognition of PHP8 union type declaration with all base types. + * + * @return void + */ + public function testPHP8UnionTypesAllBaseTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'array|bool|callable|int|float|null|Object|string', + 'return_type_token' => 8, + 'return_type_end_token' => 22, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesAllBaseTypes() + + + /** + * Verify recognition of PHP8 union type declaration with all pseudo types. + * + * Note: "Resource" is not a type, but seen as a class name. + * + * @return void + */ + public function testPHP8UnionTypesAllPseudoTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'false|MIXED|self|parent|static|iterable|Resource|void', + 'return_type_token' => 9, + 'return_type_end_token' => 23, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesAllPseudoTypes() + + + /** + * Verify recognition of PHP8 union type declaration with (illegal) nullability. + * + * @return void + */ + public function testPHP8UnionTypesNullable() + { + // Offsets are relative to the T_CLOSURE token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?int|float', + 'return_type_token' => 12, + 'return_type_end_token' => 14, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8UnionTypesNullable() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) single type null. + * + * @return void + */ + public function testPHP8PseudoTypeNull() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'null', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeNull() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) single type false. + * + * @return void + */ + public function testPHP8PseudoTypeFalse() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'false', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeFalse() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type false combined with type bool. + * + * @return void + */ + public function testPHP8PseudoTypeFalseAndBool() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'bool|false', + 'return_type_token' => 7, + 'return_type_end_token' => 9, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeFalseAndBool() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type object combined with a class name. + * + * @return void + */ + public function testPHP8ObjectAndClass() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'object|ClassName', + 'return_type_token' => 7, + 'return_type_end_token' => 9, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8ObjectAndClass() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) type iterable combined with array/Traversable. + * + * @return void + */ + public function testPHP8PseudoTypeIterableAndArray() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => 'iterable|array|Traversable', + 'return_type_token' => 7, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => false, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8PseudoTypeIterableAndArray() + + + /** + * Verify recognition of PHP8 type declaration with (illegal) duplicate types. + * + * @return void + */ + public function testPHP8DuplicateTypeInUnionWhitespaceAndComment() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'int|string|INT', + 'return_type_token' => 7, + 'return_type_end_token' => 17, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8DuplicateTypeInUnionWhitespaceAndComment() + + + /** + * Verify recognition of PHP8.1 type "never". + * + * @return void + */ + public function testPHP81NeverType() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'never', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81NeverType() + + + /** + * Verify recognition of PHP8.1 type "never" with (illegal) nullability. + * + * @return void + */ + public function testPHP81NullableNeverType() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?never', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81NullableNeverType() + + + /** + * Verify recognition of PHP8.1 intersection type declaration. + * + * @return void + */ + public function testPHP8IntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'Foo&Bar', + 'return_type_token' => 7, + 'return_type_end_token' => 9, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP8IntersectionTypes() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with more types. + * + * @return void + */ + public function testPHP81MoreIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'MyClassA&\Package\MyClassB&\Package\MyClassC', + 'return_type_token' => 7, + 'return_type_end_token' => 17, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81MoreIntersectionTypes() + + + /** + * Verify recognition of PHP8.1 intersection type declaration in arrow function. + * + * @return void + */ + public function testPHP81IntersectionArrowFunction() + { + // Offsets are relative to the T_FN token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'MyClassA&\Package\MyClassB', + 'return_type_token' => 6, + 'return_type_end_token' => 11, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81IntersectionArrowFunction() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with illegal simple types. + * + * @return void + */ + public function testPHP81IllegalIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'string&int', + 'return_type_token' => 6, + 'return_type_end_token' => 8, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81IllegalIntersectionTypes() + + + /** + * Verify recognition of PHP8.1 intersection type declaration with (illegal) nullability. + * + * @return void + */ + public function testPHP81NullableIntersectionTypes() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?Foo&Bar', + 'return_type_token' => 7, + 'return_type_end_token' => 9, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP81NullableIntersectionTypes() + + + /** + * Verify recognition of PHP 8.2 stand-alone `true` type. + * + * @return void + */ + public function testPHP82PseudoTypeTrue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?true', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP82PseudoTypeTrue() + + + /** + * Verify recognition of PHP 8.2 type declaration with (illegal) type false combined with type true. + * + * @return void + */ + public function testPHP82PseudoTypeFalseAndTrue() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'true|false', + 'return_type_token' => 7, + 'return_type_end_token' => 9, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPHP82PseudoTypeFalseAndTrue() + + + /** + * Test for incorrect tokenization of array return type declarations in PHPCS < 2.8.0. + * + * @link https://github.com/squizlabs/PHP_CodeSniffer/pull/1264 + * + * @return void + */ + public function testPhpcsIssue1264() + { + // Offsets are relative to the T_FUNCTION token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'array', + 'return_type_token' => 8, + 'return_type_end_token' => 8, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testPhpcsIssue1264() + + + /** + * Test handling of incorrect tokenization of array return type declarations for arrow functions + * in a very specific code sample in PHPCS < 3.5.4. + * + * @link https://github.com/squizlabs/PHP_CodeSniffer/issues/2773 + * + * @return void + */ + public function testArrowFunctionArrayReturnValue() + { + // Offsets are relative to the T_FN token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => 'array', + 'return_type_token' => 5, + 'return_type_end_token' => 5, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunctionArrayReturnValue() + + + /** + * Test handling of an arrow function returning by reference. + * + * @return void + */ + public function testArrowFunctionReturnByRef() + { + // Offsets are relative to the T_FN token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => false, + 'return_type' => '?string', + 'return_type_token' => 12, + 'return_type_end_token' => 12, + 'nullable_return_type' => true, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testArrowFunctionReturnByRef() + + + /** + * Test handling of function declaration nested in a ternary, where the colon for the + * return type was incorrectly tokenized as T_INLINE_ELSE prior to PHPCS 3.5.7. + * + * @return void + */ + public function testFunctionDeclarationNestedInTernaryPHPCS2975() + { + // Offsets are relative to the T_FN token. + $expected = [ + 'scope' => 'public', + 'scope_specified' => true, + 'return_type' => 'c', + 'return_type_token' => 7, + 'return_type_end_token' => 7, + 'nullable_return_type' => false, + 'is_abstract' => false, + 'is_final' => false, + 'is_static' => false, + 'has_body' => true, + ]; + + $this->getMethodPropertiesTestHelper('/* '.__FUNCTION__.' */', $expected); + + }//end testFunctionDeclarationNestedInTernaryPHPCS2975() + + + /** + * Test helper. + * + * @param string $commentString The comment which preceeds the test. + * @param array $expected The expected function output. + * + * @return void + */ + private function getMethodPropertiesTestHelper($commentString, $expected) + { + $function = $this->getTargetToken($commentString, [T_FUNCTION, T_CLOSURE, T_FN]); + $found = self::$phpcsFile->getMethodProperties($function); + + // Convert offsets to absolute positions in the token stream. + if (is_int($expected['return_type_token']) === true) { + $expected['return_type_token'] += $function; + } + + if (is_int($expected['return_type_end_token']) === true) { + $expected['return_type_end_token'] += $function; + } + + $this->assertSame($expected, $found); + + }//end getMethodPropertiesTestHelper() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.inc new file mode 100644 index 0000000..ace5a9b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.inc @@ -0,0 +1,25 @@ + 20; +} + +/* testEchoWithTabs */ +echo 'foo', + 'bar' , + 'baz'; + +/* testEndOfFile */ +echo $foo; diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.php new file mode 100644 index 0000000..5728c48 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/GetTokensAsStringTest.php @@ -0,0 +1,334 @@ + + * @copyright 2022-2024 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File:getTokensAsString method. + * + * @covers \PHP_CodeSniffer\Files\File::getTokensAsString + */ +class GetTokensAsStringTest extends AbstractMethodUnitTest +{ + + + /** + * Test passing a non-existent token pointer. + * + * @return void + */ + public function testNonExistentToken() + { + $this->expectRunTimeException('The $start position for getTokensAsString() must exist in the token stack'); + + self::$phpcsFile->getTokensAsString(100000, 10); + + }//end testNonExistentToken() + + + /** + * Test passing a non integer `$start`, like the result of a failed $phpcsFile->findNext(). + * + * @return void + */ + public function testNonIntegerStart() + { + $this->expectRunTimeException('The $start position for getTokensAsString() must exist in the token stack'); + + self::$phpcsFile->getTokensAsString(false, 10); + + }//end testNonIntegerStart() + + + /** + * Test passing a non integer `$length`. + * + * @return void + */ + public function testNonIntegerLength() + { + $result = self::$phpcsFile->getTokensAsString(10, false); + $this->assertSame('', $result); + + $result = self::$phpcsFile->getTokensAsString(10, 1.5); + $this->assertSame('', $result); + + }//end testNonIntegerLength() + + + /** + * Test passing a zero or negative `$length`. + * + * @return void + */ + public function testLengthEqualToOrLessThanZero() + { + $result = self::$phpcsFile->getTokensAsString(10, -10); + $this->assertSame('', $result); + + $result = self::$phpcsFile->getTokensAsString(10, 0); + $this->assertSame('', $result); + + }//end testLengthEqualToOrLessThanZero() + + + /** + * Test passing a `$length` beyond the end of the file. + * + * @return void + */ + public function testLengthBeyondEndOfFile() + { + $semicolon = $this->getTargetToken('/* testEndOfFile */', T_SEMICOLON); + $result = self::$phpcsFile->getTokensAsString($semicolon, 20); + $this->assertSame( + '; +', + $result + ); + + }//end testLengthBeyondEndOfFile() + + + /** + * Test getting a token set as a string. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $startTokenType The type of token(s) to look for for the start of the string. + * @param int $length Token length to get. + * @param string $expected The expected function return value. + * + * @dataProvider dataGetTokensAsString() + * + * @return void + */ + public function testGetTokensAsString($testMarker, $startTokenType, $length, $expected) + { + $start = $this->getTargetToken($testMarker, $startTokenType); + $result = self::$phpcsFile->getTokensAsString($start, $length); + $this->assertSame($expected, $result); + + }//end testGetTokensAsString() + + + /** + * Data provider. + * + * @see testGetTokensAsString() For the array format. + * + * @return array> + */ + public static function dataGetTokensAsString() + { + return [ + 'length-0' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 0, + 'expected' => '', + ], + 'length-1' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 1, + 'expected' => '1', + ], + 'length-2' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 2, + 'expected' => '1 ', + ], + 'length-3' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 3, + 'expected' => '1 +', + ], + 'length-4' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 4, + 'expected' => '1 + ', + ], + 'length-5' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 5, + 'expected' => '1 + 2', + ], + 'length-6' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 6, + 'expected' => '1 + 2 ', + ], + 'length-7' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 7, + 'expected' => '1 + 2 +', + ], + 'length-8' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 8, + 'expected' => '1 + 2 + +', + ], + 'length-9' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 9, + 'expected' => '1 + 2 + + ', + ], + 'length-10' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 10, + 'expected' => '1 + 2 + + // Comment. +', + ], + 'length-11' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 11, + 'expected' => '1 + 2 + + // Comment. + ', + ], + 'length-12' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 12, + 'expected' => '1 + 2 + + // Comment. + 3', + ], + 'length-13' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 13, + 'expected' => '1 + 2 + + // Comment. + 3 ', + ], + 'length-14' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 14, + 'expected' => '1 + 2 + + // Comment. + 3 +', + ], + 'length-34' => [ + 'testMarker' => '/* testCalculation */', + 'startTokenType' => T_LNUMBER, + 'length' => 34, + 'expected' => '1 + 2 + + // Comment. + 3 + 4 + + 5 + 6 + 7 > 20;', + ], + 'namespace' => [ + 'testMarker' => '/* testNamespace */', + 'startTokenType' => T_NAMESPACE, + 'length' => 8, + 'expected' => 'namespace Foo\Bar\Baz;', + ], + 'use-with-comments' => [ + 'testMarker' => '/* testUseWithComments */', + 'startTokenType' => T_USE, + 'length' => 17, + 'expected' => 'use Foo /*comment*/ \ Bar + // phpcs:ignore Stnd.Cat.Sniff -- For reasons. + \ Bah;', + ], + 'echo-with-tabs' => [ + 'testMarker' => '/* testEchoWithTabs */', + 'startTokenType' => T_ECHO, + 'length' => 13, + 'expected' => 'echo \'foo\', + \'bar\' , + \'baz\';', + ], + 'end-of-file' => [ + 'testMarker' => '/* testEndOfFile */', + 'startTokenType' => T_ECHO, + 'length' => 4, + 'expected' => 'echo $foo;', + ], + ]; + + }//end dataGetTokensAsString() + + + /** + * Test getting a token set as a string with the original, non tab-replaced content. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int|string $startTokenType The type of token(s) to look for for the start of the string. + * @param int $length Token length to get. + * @param string $expected The expected function return value. + * + * @dataProvider dataGetOrigContent() + * + * @return void + */ + public function testGetOrigContent($testMarker, $startTokenType, $length, $expected) + { + $start = $this->getTargetToken($testMarker, $startTokenType); + $result = self::$phpcsFile->getTokensAsString($start, $length, true); + $this->assertSame($expected, $result); + + }//end testGetOrigContent() + + + /** + * Data provider. + * + * @see testGetOrigContent() For the array format. + * + * @return array> + */ + public static function dataGetOrigContent() + { + return [ + 'use-with-comments' => [ + 'testMarker' => '/* testUseWithComments */', + 'startTokenType' => T_USE, + 'length' => 17, + 'expected' => 'use Foo /*comment*/ \ Bar + // phpcs:ignore Stnd.Cat.Sniff -- For reasons. + \ Bah;', + ], + 'echo-with-tabs' => [ + 'testMarker' => '/* testEchoWithTabs */', + 'startTokenType' => T_ECHO, + 'length' => 13, + 'expected' => 'echo \'foo\', + \'bar\' , + \'baz\';', + ], + 'end-of-file' => [ + 'testMarker' => '/* testEndOfFile */', + 'startTokenType' => T_ECHO, + 'length' => 4, + 'expected' => 'echo $foo;', + ], + ]; + + }//end dataGetOrigContent() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.inc new file mode 100644 index 0000000..93c7acc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.inc @@ -0,0 +1,210 @@ + $first, 'b' => $something & $somethingElse ]; + +/* testBitwiseAndF */ +$a = array( 'a' => $first, 'b' => $something & \MyClass::$somethingElse ); + +/* testBitwiseAndG */ +$a = $something & $somethingElse; + +/* testBitwiseAndH */ +function myFunction($a = 10 & 20) {} + +/* testBitwiseAndI */ +$closure = function ($a = MY_CONSTANT & parent::OTHER_CONSTANT) {}; + +/* testFunctionReturnByReference */ +function &myFunction() {} + +/* testFunctionPassByReferenceA */ +function myFunction( &$a ) {} + +/* testFunctionPassByReferenceB */ +function myFunction( $a, &$b ) {} + +/* testFunctionPassByReferenceC */ +$closure = function ( &$a ) {}; + +/* testFunctionPassByReferenceD */ +$closure = function ( $a, &$b ) {}; + +/* testFunctionPassByReferenceE */ +function myFunction(array &$one) {} + +/* testFunctionPassByReferenceF */ +$closure = function (\MyClass &$one) {}; + +/* testFunctionPassByReferenceG */ +$closure = function ($param, &...$moreParams) {}; + +/* testForeachValueByReference */ +foreach( $array as $key => &$value ) {} + +/* testForeachKeyByReference */ +foreach( $array as &$key => $value ) {} + +/* testArrayValueByReferenceA */ +$a = [ 'a' => &$something ]; + +/* testArrayValueByReferenceB */ +$a = [ 'a' => $something, 'b' => &$somethingElse ]; + +/* testArrayValueByReferenceC */ +$a = [ &$something ]; + +/* testArrayValueByReferenceD */ +$a = [ $something, &$somethingElse ]; + +/* testArrayValueByReferenceE */ +$a = array( 'a' => &$something ); + +/* testArrayValueByReferenceF */ +$a = array( 'a' => $something, 'b' => &$somethingElse ); + +/* testArrayValueByReferenceG */ +$a = array( &$something ); + +/* testArrayValueByReferenceH */ +$a = array( $something, &$somethingElse ); + +/* testAssignByReferenceA */ +$b = &$something; + +/* testAssignByReferenceB */ +$b =& $something; + +/* testAssignByReferenceC */ +$b .= &$something; + +/* testAssignByReferenceD */ +$myValue = &$obj->getValue(); + +/* testAssignByReferenceE */ +$collection = &collector(); + +/* testAssignByReferenceF */ +$collection ??= &collector(); + +/* testShortListAssignByReferenceNoKeyA */ +[ + &$a, + /* testShortListAssignByReferenceNoKeyB */ + &$b, + /* testNestedShortListAssignByReferenceNoKey */ + [$c, &$d] +] = $array; + +/* testLongListAssignByReferenceNoKeyA */ +list($a, &$b, list(/* testLongListAssignByReferenceNoKeyB */ &$c, /* testLongListAssignByReferenceNoKeyC */ &$d)) = $array; + +[ + /* testNestedShortListAssignByReferenceWithKeyA */ + 'a' => [&$a, $b], + /* testNestedShortListAssignByReferenceWithKeyB */ + 'b' => [$c, &$d] +] = $array; + + +/* testLongListAssignByReferenceWithKeyA */ +list(get_key()[1] => &$e) = [1, 2, 3]; + +/* testPassByReferenceA */ +functionCall(&$something, $somethingElse); + +/* testPassByReferenceB */ +functionCall($something, &$somethingElse); + +/* testPassByReferenceC */ +functionCall($something, &$this->somethingElse); + +/* testPassByReferenceD */ +functionCall($something, &self::$somethingElse); + +/* testPassByReferenceE */ +functionCall($something, &parent::$somethingElse); + +/* testPassByReferenceF */ +functionCall($something, &static::$somethingElse); + +/* testPassByReferenceG */ +functionCall($something, &SomeClass::$somethingElse); + +/* testPassByReferenceH */ +functionCall(&\SomeClass::$somethingElse); + +/* testPassByReferenceI */ +functionCall($something, &\SomeNS\SomeClass::$somethingElse); + +/* testPassByReferenceJ */ +functionCall($something, &namespace\SomeClass::$somethingElse); + +/* testPassByReferencePartiallyQualifiedName */ +functionCall($something, &Sub\Level\SomeClass::$somethingElse); + +/* testNewByReferenceA */ +$foobar2 = &new Foobar(); + +/* testNewByReferenceB */ +functionCall( $something , &new Foobar() ); + +/* testUseByReference */ +$closure = function() use (&$var){}; + +/* testUseByReferenceWithCommentFirstParam */ +$closure = function() use /*comment*/ (&$this->value){}; + +/* testUseByReferenceWithCommentSecondParam */ +$closure = function() use /*comment*/ ($varA, &$varB){}; + +/* testArrowFunctionReturnByReference */ +fn&($x) => $x; + +$closure = function ( + /* testBitwiseAndExactParameterA */ + $a = MY_CONSTANT & parent::OTHER_CONSTANT, + /* testPassByReferenceExactParameterB */ + &$b, + /* testPassByReferenceExactParameterC */ + &...$c, + /* testBitwiseAndExactParameterD */ + $d = E_NOTICE & E_STRICT, +) {}; + +// Issue PHPCS#3049. +/* testArrowFunctionPassByReferenceA */ +$fn = fn(array &$one) => 1; + +/* testArrowFunctionPassByReferenceB */ +$fn = fn($param, &...$moreParams) => 1; + +/* testClosureReturnByReference */ +$closure = function &($param) use ($value) {}; + +/* testBitwiseAndArrowFunctionInDefault */ +$fn = fn( $one = E_NOTICE & E_STRICT) => 1; + +/* testTokenizerIssue1284PHPCSlt280A */ +if ($foo) {} +[&$a, /* testTokenizerIssue1284PHPCSlt280B */ &$b] = $c; + +/* testTokenizerIssue1284PHPCSlt280C */ +if ($foo) {} +[&$a, $b]; diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.php new file mode 100644 index 0000000..929779d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/File/IsReferenceTest.php @@ -0,0 +1,358 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\File; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Files\File::isReference method. + * + * @covers \PHP_CodeSniffer\Files\File::isReference + */ +class IsReferenceTest extends AbstractMethodUnitTest +{ + + + /** + * Test that false is returned when a non-"bitwise and" token is passed. + * + * @return void + */ + public function testNotBitwiseAndToken() + { + $target = $this->getTargetToken('/* testBitwiseAndA */', T_STRING); + $this->assertFalse(self::$phpcsFile->isReference($target)); + + }//end testNotBitwiseAndToken() + + + /** + * Test correctly identifying whether a "bitwise and" token is a reference or not. + * + * @param string $identifier Comment which precedes the test case. + * @param bool $expected Expected function output. + * + * @dataProvider dataIsReference + * + * @return void + */ + public function testIsReference($identifier, $expected) + { + $bitwiseAnd = $this->getTargetToken($identifier, T_BITWISE_AND); + $result = self::$phpcsFile->isReference($bitwiseAnd); + $this->assertSame($expected, $result); + + }//end testIsReference() + + + /** + * Data provider for the IsReference test. + * + * @see testIsReference() + * + * @return array> + */ + public function dataIsReference() + { + return [ + 'issue-1971-list-first-in-file' => [ + 'testMarker' => '/* testTokenizerIssue1971PHPCSlt330gt271A */', + 'expected' => true, + ], + 'issue-1971-list-first-in-file-nested' => [ + 'testMarker' => '/* testTokenizerIssue1971PHPCSlt330gt271B */', + 'expected' => true, + ], + 'bitwise and: param in function call' => [ + 'testMarker' => '/* testBitwiseAndA */', + 'expected' => false, + ], + 'bitwise and: in unkeyed short array, first value' => [ + 'testMarker' => '/* testBitwiseAndB */', + 'expected' => false, + ], + 'bitwise and: in unkeyed short array, last value' => [ + 'testMarker' => '/* testBitwiseAndC */', + 'expected' => false, + ], + 'bitwise and: in unkeyed long array, last value' => [ + 'testMarker' => '/* testBitwiseAndD */', + 'expected' => false, + ], + 'bitwise and: in keyed short array, last value' => [ + 'testMarker' => '/* testBitwiseAndE */', + 'expected' => false, + ], + 'bitwise and: in keyed long array, last value' => [ + 'testMarker' => '/* testBitwiseAndF */', + 'expected' => false, + ], + 'bitwise and: in assignment' => [ + 'testMarker' => '/* testBitwiseAndG */', + 'expected' => false, + ], + 'bitwise and: in param default value in function declaration' => [ + 'testMarker' => '/* testBitwiseAndH */', + 'expected' => false, + ], + 'bitwise and: in param default value in closure declaration' => [ + 'testMarker' => '/* testBitwiseAndI */', + 'expected' => false, + ], + 'reference: function declared to return by reference' => [ + 'testMarker' => '/* testFunctionReturnByReference */', + 'expected' => true, + ], + 'reference: only param in function declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceA */', + 'expected' => true, + ], + 'reference: last param in function declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceB */', + 'expected' => true, + ], + 'reference: only param in closure declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceC */', + 'expected' => true, + ], + 'reference: last param in closure declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceD */', + 'expected' => true, + ], + 'reference: typed param in function declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceE */', + 'expected' => true, + ], + 'reference: typed param in closure declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceF */', + 'expected' => true, + ], + 'reference: variadic param in function declaration, pass by reference' => [ + 'testMarker' => '/* testFunctionPassByReferenceG */', + 'expected' => true, + ], + 'reference: foreach value' => [ + 'testMarker' => '/* testForeachValueByReference */', + 'expected' => true, + ], + 'reference: foreach key' => [ + 'testMarker' => '/* testForeachKeyByReference */', + 'expected' => true, + ], + 'reference: keyed short array, first value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceA */', + 'expected' => true, + ], + 'reference: keyed short array, last value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceB */', + 'expected' => true, + ], + 'reference: unkeyed short array, only value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceC */', + 'expected' => true, + ], + 'reference: unkeyed short array, last value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceD */', + 'expected' => true, + ], + 'reference: keyed long array, first value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceE */', + 'expected' => true, + ], + 'reference: keyed long array, last value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceF */', + 'expected' => true, + ], + 'reference: unkeyed long array, only value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceG */', + 'expected' => true, + ], + 'reference: unkeyed long array, last value, value by reference' => [ + 'testMarker' => '/* testArrayValueByReferenceH */', + 'expected' => true, + ], + 'reference: variable, assign by reference' => [ + 'testMarker' => '/* testAssignByReferenceA */', + 'expected' => true, + ], + 'reference: variable, assign by reference, spacing variation' => [ + 'testMarker' => '/* testAssignByReferenceB */', + 'expected' => true, + ], + 'reference: variable, assign by reference, concat assign' => [ + 'testMarker' => '/* testAssignByReferenceC */', + 'expected' => true, + ], + 'reference: property, assign by reference' => [ + 'testMarker' => '/* testAssignByReferenceD */', + 'expected' => true, + ], + 'reference: function return value, assign by reference' => [ + 'testMarker' => '/* testAssignByReferenceE */', + 'expected' => true, + ], + 'reference: function return value, assign by reference, null coalesce assign' => [ + 'testMarker' => '/* testAssignByReferenceF */', + 'expected' => true, + ], + 'reference: unkeyed short list, first var, assign by reference' => [ + 'testMarker' => '/* testShortListAssignByReferenceNoKeyA */', + 'expected' => true, + ], + 'reference: unkeyed short list, second var, assign by reference' => [ + 'testMarker' => '/* testShortListAssignByReferenceNoKeyB */', + 'expected' => true, + ], + 'reference: unkeyed short list, nested var, assign by reference' => [ + 'testMarker' => '/* testNestedShortListAssignByReferenceNoKey */', + 'expected' => true, + ], + 'reference: unkeyed long list, second var, assign by reference' => [ + 'testMarker' => '/* testLongListAssignByReferenceNoKeyA */', + 'expected' => true, + ], + 'reference: unkeyed long list, first nested var, assign by reference' => [ + 'testMarker' => '/* testLongListAssignByReferenceNoKeyB */', + 'expected' => true, + ], + 'reference: unkeyed long list, last nested var, assign by reference' => [ + 'testMarker' => '/* testLongListAssignByReferenceNoKeyC */', + 'expected' => true, + ], + 'reference: keyed short list, first nested var, assign by reference' => [ + 'testMarker' => '/* testNestedShortListAssignByReferenceWithKeyA */', + 'expected' => true, + ], + 'reference: keyed short list, last nested var, assign by reference' => [ + 'testMarker' => '/* testNestedShortListAssignByReferenceWithKeyB */', + 'expected' => true, + ], + 'reference: keyed long list, only var, assign by reference' => [ + 'testMarker' => '/* testLongListAssignByReferenceWithKeyA */', + 'expected' => true, + ], + 'reference: first param in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceA */', + 'expected' => true, + ], + 'reference: last param in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceB */', + 'expected' => true, + ], + 'reference: property in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceC */', + 'expected' => true, + ], + 'reference: hierarchical self property in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceD */', + 'expected' => true, + ], + 'reference: hierarchical parent property in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceE */', + 'expected' => true, + ], + 'reference: hierarchical static property in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceF */', + 'expected' => true, + ], + 'reference: static property in function call, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceG */', + 'expected' => true, + ], + 'reference: static property in function call, first with FQN, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceH */', + 'expected' => true, + ], + 'reference: static property in function call, last with FQN, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceI */', + 'expected' => true, + ], + 'reference: static property in function call, last with namespace relative name, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceJ */', + 'expected' => true, + ], + 'reference: static property in function call, last with PQN, pass by reference' => [ + 'testMarker' => '/* testPassByReferencePartiallyQualifiedName */', + 'expected' => true, + ], + 'reference: new by reference' => [ + 'testMarker' => '/* testNewByReferenceA */', + 'expected' => true, + ], + 'reference: new by reference as function call param' => [ + 'testMarker' => '/* testNewByReferenceB */', + 'expected' => true, + ], + 'reference: closure use by reference' => [ + 'testMarker' => '/* testUseByReference */', + 'expected' => true, + ], + 'reference: closure use by reference, first param, with comment' => [ + 'testMarker' => '/* testUseByReferenceWithCommentFirstParam */', + 'expected' => true, + ], + 'reference: closure use by reference, last param, with comment' => [ + 'testMarker' => '/* testUseByReferenceWithCommentSecondParam */', + 'expected' => true, + ], + 'reference: arrow fn declared to return by reference' => [ + 'testMarker' => '/* testArrowFunctionReturnByReference */', + 'expected' => true, + ], + 'bitwise and: first param default value in closure declaration' => [ + 'testMarker' => '/* testBitwiseAndExactParameterA */', + 'expected' => false, + ], + 'reference: param in closure declaration, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceExactParameterB */', + 'expected' => true, + ], + 'reference: variadic param in closure declaration, pass by reference' => [ + 'testMarker' => '/* testPassByReferenceExactParameterC */', + 'expected' => true, + ], + 'bitwise and: last param default value in closure declaration' => [ + 'testMarker' => '/* testBitwiseAndExactParameterD */', + 'expected' => false, + ], + 'reference: typed param in arrow fn declaration, pass by reference' => [ + 'testMarker' => '/* testArrowFunctionPassByReferenceA */', + 'expected' => true, + ], + 'reference: variadic param in arrow fn declaration, pass by reference' => [ + 'testMarker' => '/* testArrowFunctionPassByReferenceB */', + 'expected' => true, + ], + 'reference: closure declared to return by reference' => [ + 'testMarker' => '/* testClosureReturnByReference */', + 'expected' => true, + ], + 'bitwise and: param default value in arrow fn declaration' => [ + 'testMarker' => '/* testBitwiseAndArrowFunctionInDefault */', + 'expected' => false, + ], + 'issue-1284-short-list-directly-after-close-curly-control-structure' => [ + 'testMarker' => '/* testTokenizerIssue1284PHPCSlt280A */', + 'expected' => true, + ], + 'issue-1284-short-list-directly-after-close-curly-control-structure-second-item' => [ + 'testMarker' => '/* testTokenizerIssue1284PHPCSlt280B */', + 'expected' => true, + ], + 'issue-1284-short-array-directly-after-close-curly-control-structure' => [ + 'testMarker' => '/* testTokenizerIssue1284PHPCSlt280C */', + 'expected' => true, + ], + ]; + + }//end dataIsReference() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Filters/AbstractFilterTestCase.php b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/AbstractFilterTestCase.php new file mode 100644 index 0000000..b867d7a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/AbstractFilterTestCase.php @@ -0,0 +1,227 @@ + + * @copyright 2023 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Filters; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Filters\Filter; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; +use RecursiveIteratorIterator; + +/** + * Base functionality and utilities for testing Filter classes. + */ +abstract class AbstractFilterTestCase extends TestCase +{ + + /** + * The Config object. + * + * @var \PHP_CodeSniffer\Config + */ + protected static $config; + + /** + * The Ruleset object. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected static $ruleset; + + + /** + * Initialize the config and ruleset objects. + * + * @beforeClass + * + * @return void + */ + public static function initializeConfigAndRuleset() + { + self::$config = new Config(['--standard=PSR1', '--extensions=php,inc/php,js,css', '--report-width=80']); + self::$ruleset = new Ruleset(self::$config); + + }//end initializeConfigAndRuleset() + + + /** + * Helper method to retrieve a mock object for a Filter class. + * + * The `setMethods()` method was silently deprecated in PHPUnit 9 and removed in PHPUnit 10. + * + * Note: direct access to the `getMockBuilder()` method is soft deprecated as of PHPUnit 10, + * and expected to be hard deprecated in PHPUnit 11 and removed in PHPUnit 12. + * Dealing with that is something for a later iteration of the test suite. + * + * @param string $className Fully qualified name of the class under test. + * @param array $constructorArgs Optional. Array of parameters to pass to the class constructor. + * @param array|null $methodsToMock Optional. The methods to mock in the class under test. + * Needed for PHPUnit cross-version support as PHPUnit 4.x does + * not have a `setMethodsExcept()` method yet. + * If not passed, no methods will be replaced. + * + * @return \PHPUnit\Framework\MockObject\MockObject + */ + protected function getMockedClass($className, array $constructorArgs=[], $methodsToMock=null) + { + $mockedObj = $this->getMockBuilder($className); + + if (\method_exists($mockedObj, 'onlyMethods') === true) { + // PHPUnit 8+. + if (is_array($methodsToMock) === true) { + return $mockedObj + ->setConstructorArgs($constructorArgs) + ->onlyMethods($methodsToMock) + ->getMock(); + } + + return $mockedObj->getMock() + ->setConstructorArgs($constructorArgs); + } + + // PHPUnit < 8. + return $mockedObj + ->setConstructorArgs($constructorArgs) + ->setMethods($methodsToMock) + ->getMock(); + + }//end getMockedClass() + + + /** + * Retrieve an array of files which were accepted by a filter. + * + * @param \PHP_CodeSniffer\Filters\Filter $filter The Filter object under test. + * + * @return array + */ + protected function getFilteredResultsAsArray(Filter $filter) + { + $iterator = new RecursiveIteratorIterator($filter); + $files = []; + foreach ($iterator as $file) { + $files[] = $file; + } + + return $files; + + }//end getFilteredResultsAsArray() + + + /** + * Retrieve the basedir to use for tests using the `getFakeFileList()` method. + * + * @return string + */ + protected static function getBaseDir() + { + return dirname(dirname(dirname(__DIR__))); + + }//end getBaseDir() + + + /** + * Retrieve a file list containing a range of paths for testing purposes. + * + * This list **must** contain files which exist in this project (well, except for some which don't exist + * purely for testing purposes), as `realpath()` is used in the logic under test and `realpath()` will + * return `false` for any non-existent files, which will automatically filter them out before + * we get to the code under test. + * + * Note this list does not include `.` and `..` as \PHP_CodeSniffer\Files\FileList uses `SKIP_DOTS`. + * + * @return array + */ + protected static function getFakeFileList() + { + $basedir = self::getBaseDir(); + return [ + $basedir.'/.gitignore', + $basedir.'/.yamllint.yml', + $basedir.'/phpcs.xml', + $basedir.'/phpcs.xml.dist', + $basedir.'/autoload.php', + $basedir.'/bin', + $basedir.'/bin/phpcs', + $basedir.'/bin/phpcs.bat', + $basedir.'/scripts', + $basedir.'/scripts/build-phar.php', + $basedir.'/src', + $basedir.'/src/WillNotExist.php', + $basedir.'/src/WillNotExist.bak', + $basedir.'/src/WillNotExist.orig', + $basedir.'/src/Ruleset.php', + $basedir.'/src/Generators', + $basedir.'/src/Generators/Markdown.php', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Generic', + $basedir.'/src/Standards/Generic/Docs', + $basedir.'/src/Standards/Generic/Docs/Classes', + $basedir.'/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml', + $basedir.'/src/Standards/Generic/Sniffs', + $basedir.'/src/Standards/Generic/Sniffs/Classes', + $basedir.'/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + $basedir.'/src/Standards/Generic/Tests', + $basedir.'/src/Standards/Generic/Tests/Classes', + $basedir.'/src/Standards/Generic/Tests/Classes/DuplicateClassNameUnitTest.1.inc', + // Will rarely exist when running the tests. + $basedir.'/src/Standards/Generic/Tests/Classes/DuplicateClassNameUnitTest.1.inc.bak', + $basedir.'/src/Standards/Generic/Tests/Classes/DuplicateClassNameUnitTest.2.inc', + $basedir.'/src/Standards/Generic/Tests/Classes/DuplicateClassNameUnitTest.php', + $basedir.'/src/Standards/Squiz', + $basedir.'/src/Standards/Squiz/Docs', + $basedir.'/src/Standards/Squiz/Docs/WhiteSpace', + $basedir.'/src/Standards/Squiz/Docs/WhiteSpace/SemicolonSpacingStandard.xml', + $basedir.'/src/Standards/Squiz/Sniffs', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php', + $basedir.'/src/Standards/Squiz/Tests', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php', + ]; + + }//end getFakeFileList() + + + /** + * Translate Linux paths to Windows paths, when necessary. + * + * These type of tests should be able to run and pass on both *nix as well as Windows + * based dev systems. This method is a helper to allow for this. + * + * @param array $paths A single or multi-dimensional array containing + * file paths. + * + * @return array + */ + protected static function mapPathsToRuntimeOs(array $paths) + { + if (DIRECTORY_SEPARATOR !== '\\') { + return $paths; + } + + foreach ($paths as $key => $value) { + if (is_string($value) === true) { + $paths[$key] = strtr($value, '/', '\\\\'); + } else if (is_array($value) === true) { + $paths[$key] = self::mapPathsToRuntimeOs($value); + } + } + + return $paths; + + }//end mapPathsToRuntimeOs() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.php new file mode 100644 index 0000000..fa3c834 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.php @@ -0,0 +1,110 @@ + + * @author Juliette Reinders Folmer + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Filters\Filter; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Filters\Filter; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Tests\Core\Filters\AbstractFilterTestCase; +use RecursiveArrayIterator; + +/** + * Tests for the \PHP_CodeSniffer\Filters\Filter::accept method. + * + * @covers \PHP_CodeSniffer\Filters\Filter + */ +class AcceptTest extends AbstractFilterTestCase +{ + + + /** + * Initialize the config and ruleset objects based on the `AcceptTest.xml` ruleset file. + * + * @beforeClass + * + * @return void + */ + public static function initializeConfigAndRuleset() + { + $standard = __DIR__.'/'.basename(__FILE__, '.php').'.xml'; + self::$config = new Config(["--standard=$standard", '--ignore=*/somethingelse/*', '--report-width=80']); + self::$ruleset = new Ruleset(self::$config); + + }//end initializeConfigAndRuleset() + + + /** + * Test filtering a file list for excluded paths. + * + * @param array $inputPaths List of file paths to be filtered. + * @param array $expectedOutput Expected filtering result. + * + * @dataProvider dataExcludePatterns + * + * @return void + */ + public function testExcludePatterns($inputPaths, $expectedOutput) + { + $fakeDI = new RecursiveArrayIterator($inputPaths); + $filter = new Filter($fakeDI, '/', self::$config, self::$ruleset); + + $this->assertEquals($expectedOutput, $this->getFilteredResultsAsArray($filter)); + + }//end testExcludePatterns() + + + /** + * Data provider. + * + * @see testExcludePatterns + * + * @return array>> + */ + public static function dataExcludePatterns() + { + $testCases = [ + // Test top-level exclude patterns. + 'Non-sniff specific path based excludes from ruleset and command line are respected and don\'t filter out too much' => [ + 'inputPaths' => [ + '/path/to/src/Main.php', + '/path/to/src/Something/Main.php', + '/path/to/src/Somethingelse/Main.php', + '/path/to/src/SomethingelseEvenLonger/Main.php', + '/path/to/src/Other/Main.php', + ], + 'expectedOutput' => [ + '/path/to/src/Main.php', + '/path/to/src/SomethingelseEvenLonger/Main.php', + ], + ], + + // Test ignoring standard/sniff specific exclude patterns. + 'Filter should not act on standard/sniff specific exclude patterns' => [ + 'inputPaths' => [ + '/path/to/src/generic-project/Main.php', + '/path/to/src/generic/Main.php', + '/path/to/src/anything-generic/Main.php', + ], + 'expectedOutput' => [ + '/path/to/src/generic-project/Main.php', + '/path/to/src/generic/Main.php', + '/path/to/src/anything-generic/Main.php', + ], + ], + ]; + + // Allow these tests to work on Windows as well. + return self::mapPathsToRuntimeOs($testCases); + + }//end dataExcludePatterns() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.xml new file mode 100644 index 0000000..3d3e1de --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/Filter/AcceptTest.xml @@ -0,0 +1,16 @@ + + + Ruleset to test the filtering based on exclude patterns. + + + */something/* + + */Other/Main\.php$ + + + + /anything/* + + /YetAnother/Main\.php + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitModifiedTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitModifiedTest.php new file mode 100644 index 0000000..b3d11b6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitModifiedTest.php @@ -0,0 +1,260 @@ + + * @copyright 2023 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Filters; + +use PHP_CodeSniffer\Filters\GitModified; +use PHP_CodeSniffer\Tests\Core\Filters\AbstractFilterTestCase; +use RecursiveArrayIterator; +use ReflectionMethod; + +/** + * Tests for the \PHP_CodeSniffer\Filters\GitModified class. + * + * @covers \PHP_CodeSniffer\Filters\GitModified + */ +class GitModifiedTest extends AbstractFilterTestCase +{ + + + /** + * Test filtering a file list for excluded paths. + * + * @return void + */ + public function testFileNamePassesAsBasePathWillTranslateToDirname() + { + $rootFile = self::getBaseDir().'/autoload.php'; + + $fakeDI = new RecursiveArrayIterator(self::getFakeFileList()); + $constructorArgs = [ + $fakeDI, + $rootFile, + self::$config, + self::$ruleset, + ]; + $mockObj = $this->getMockedClass('PHP_CodeSniffer\Filters\GitModified', $constructorArgs, ['exec']); + + $mockObj->expects($this->once()) + ->method('exec') + ->willReturn(['autoload.php']); + + $this->assertEquals([$rootFile], $this->getFilteredResultsAsArray($mockObj)); + + }//end testFileNamePassesAsBasePathWillTranslateToDirname() + + + /** + * Test filtering a file list for excluded paths. + * + * @param array $inputPaths List of file paths to be filtered. + * @param array $outputGitModified Simulated "git modified" output. + * @param array $expectedOutput Expected filtering result. + * + * @dataProvider dataAcceptOnlyGitModified + * + * @return void + */ + public function testAcceptOnlyGitModified($inputPaths, $outputGitModified, $expectedOutput) + { + $fakeDI = new RecursiveArrayIterator($inputPaths); + $constructorArgs = [ + $fakeDI, + self::getBaseDir(), + self::$config, + self::$ruleset, + ]; + $mockObj = $this->getMockedClass('PHP_CodeSniffer\Filters\GitModified', $constructorArgs, ['exec']); + + $mockObj->expects($this->once()) + ->method('exec') + ->willReturn($outputGitModified); + + $this->assertEquals($expectedOutput, $this->getFilteredResultsAsArray($mockObj)); + + }//end testAcceptOnlyGitModified() + + + /** + * Data provider. + * + * @see testAcceptOnlyGitModified + * + * @return array>> + */ + public static function dataAcceptOnlyGitModified() + { + $basedir = self::getBaseDir(); + $fakeFileList = self::getFakeFileList(); + + $testCases = [ + 'no files marked as git modified' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => [], + 'expectedOutput' => [], + ], + + 'files marked as git modified which don\'t actually exist' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => [ + 'src/WillNotExist.php', + 'src/WillNotExist.bak', + 'src/WillNotExist.orig', + ], + 'expectedOutput' => [], + ], + + 'single file marked as git modified - file in root dir' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => ['autoload.php'], + 'expectedOutput' => [ + $basedir.'/autoload.php', + ], + ], + 'single file marked as git modified - file in sub dir' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => ['src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php'], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Generic', + $basedir.'/src/Standards/Generic/Sniffs', + $basedir.'/src/Standards/Generic/Sniffs/Classes', + $basedir.'/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + ], + + 'multiple files marked as git modified, none valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => [ + '.gitignore', + 'phpcs.xml.dist', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed', + ], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Squiz', + $basedir.'/src/Standards/Squiz/Tests', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace', + ], + ], + + 'multiple files marked as git modified, only one file valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => [ + '.gitignore', + 'src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml', + 'src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Generic', + $basedir.'/src/Standards/Generic/Docs', + $basedir.'/src/Standards/Generic/Docs/Classes', + $basedir.'/src/Standards/Generic/Sniffs', + $basedir.'/src/Standards/Generic/Sniffs/Classes', + $basedir.'/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + ], + + 'multiple files marked as git modified, multiple files valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitModified' => [ + '.yamllint.yml', + 'autoload.php', + 'src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php', + ], + 'expectedOutput' => [ + $basedir.'/autoload.php', + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Squiz', + $basedir.'/src/Standards/Squiz/Sniffs', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php', + $basedir.'/src/Standards/Squiz/Tests', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php', + ], + ], + ]; + + return $testCases; + + }//end dataAcceptOnlyGitModified() + + + /** + * Test filtering a file list for excluded paths. + * + * @param string $cmd Command to run. + * @param array $expected Expected return value. + * + * @dataProvider dataExecAlwaysReturnsArray + * + * @return void + */ + public function testExecAlwaysReturnsArray($cmd, $expected) + { + $fakeDI = new RecursiveArrayIterator(self::getFakeFileList()); + $filter = new GitModified($fakeDI, '/', self::$config, self::$ruleset); + + $reflMethod = new ReflectionMethod($filter, 'exec'); + $reflMethod->setAccessible(true); + $result = $reflMethod->invoke($filter, $cmd); + + $this->assertSame($expected, $result); + + }//end testExecAlwaysReturnsArray() + + + /** + * Data provider. + * + * @see testExecAlwaysReturnsArray + * + * {@internal Missing: test with a command which yields a `false` return value. + * JRF: I've not managed to find a command which does so, let alone one, which then + * doesn't have side-effects of uncatchable output while running the tests.} + * + * @return array>> + */ + public static function dataExecAlwaysReturnsArray() + { + return [ + 'valid command which won\'t have any output unless files in the bin dir have been modified' => [ + // Largely using the command used in the filter, but only checking the bin dir. + // This should prevent the test unexpectedly failing during local development (in most cases). + 'cmd' => 'git ls-files -o -m --exclude-standard -- '.escapeshellarg(self::getBaseDir().'/bin'), + 'expected' => [], + ], + 'valid command which will have output' => [ + 'cmd' => 'git ls-files --exclude-standard -- '.escapeshellarg(self::getBaseDir().'/bin'), + 'expected' => [ + 'bin/phpcbf', + 'bin/phpcbf.bat', + 'bin/phpcs', + 'bin/phpcs.bat', + ], + ], + ]; + + }//end dataExecAlwaysReturnsArray() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitStagedTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitStagedTest.php new file mode 100644 index 0000000..ebf761c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Filters/GitStagedTest.php @@ -0,0 +1,260 @@ + + * @copyright 2023 PHPCSStandards Contributors + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Filters; + +use PHP_CodeSniffer\Filters\GitStaged; +use PHP_CodeSniffer\Tests\Core\Filters\AbstractFilterTestCase; +use RecursiveArrayIterator; +use ReflectionMethod; + +/** + * Tests for the \PHP_CodeSniffer\Filters\GitStaged class. + * + * @covers \PHP_CodeSniffer\Filters\GitStaged + */ +class GitStagedTest extends AbstractFilterTestCase +{ + + + /** + * Test filtering a file list for excluded paths. + * + * @return void + */ + public function testFileNamePassesAsBasePathWillTranslateToDirname() + { + $rootFile = self::getBaseDir().'/autoload.php'; + + $fakeDI = new RecursiveArrayIterator(self::getFakeFileList()); + $constructorArgs = [ + $fakeDI, + $rootFile, + self::$config, + self::$ruleset, + ]; + $mockObj = $this->getMockedClass('PHP_CodeSniffer\Filters\GitStaged', $constructorArgs, ['exec']); + + $mockObj->expects($this->once()) + ->method('exec') + ->willReturn(['autoload.php']); + + $this->assertEquals([$rootFile], $this->getFilteredResultsAsArray($mockObj)); + + }//end testFileNamePassesAsBasePathWillTranslateToDirname() + + + /** + * Test filtering a file list for excluded paths. + * + * @param array $inputPaths List of file paths to be filtered. + * @param array $outputGitStaged Simulated "git staged" output. + * @param array $expectedOutput Expected filtering result. + * + * @dataProvider dataAcceptOnlyGitStaged + * + * @return void + */ + public function testAcceptOnlyGitStaged($inputPaths, $outputGitStaged, $expectedOutput) + { + $fakeDI = new RecursiveArrayIterator($inputPaths); + $constructorArgs = [ + $fakeDI, + self::getBaseDir(), + self::$config, + self::$ruleset, + ]; + $mockObj = $this->getMockedClass('PHP_CodeSniffer\Filters\GitStaged', $constructorArgs, ['exec']); + + $mockObj->expects($this->once()) + ->method('exec') + ->willReturn($outputGitStaged); + + $this->assertEquals($expectedOutput, $this->getFilteredResultsAsArray($mockObj)); + + }//end testAcceptOnlyGitStaged() + + + /** + * Data provider. + * + * @see testAcceptOnlyGitStaged + * + * @return array>> + */ + public static function dataAcceptOnlyGitStaged() + { + $basedir = self::getBaseDir(); + $fakeFileList = self::getFakeFileList(); + + $testCases = [ + 'no files marked as git modified' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => [], + 'expectedOutput' => [], + ], + + 'files marked as git modified which don\'t actually exist' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => [ + 'src/WillNotExist.php', + 'src/WillNotExist.bak', + 'src/WillNotExist.orig', + ], + 'expectedOutput' => [], + ], + + 'single file marked as git modified - file in root dir' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => ['autoload.php'], + 'expectedOutput' => [ + $basedir.'/autoload.php', + ], + ], + 'single file marked as git modified - file in sub dir' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => ['src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php'], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Generic', + $basedir.'/src/Standards/Generic/Sniffs', + $basedir.'/src/Standards/Generic/Sniffs/Classes', + $basedir.'/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + ], + + 'multiple files marked as git modified, none valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => [ + '.gitignore', + 'phpcs.xml.dist', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed', + ], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Squiz', + $basedir.'/src/Standards/Squiz/Tests', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace', + ], + ], + + 'multiple files marked as git modified, only one file valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => [ + '.gitignore', + 'src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml', + 'src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + 'expectedOutput' => [ + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Generic', + $basedir.'/src/Standards/Generic/Docs', + $basedir.'/src/Standards/Generic/Docs/Classes', + $basedir.'/src/Standards/Generic/Sniffs', + $basedir.'/src/Standards/Generic/Sniffs/Classes', + $basedir.'/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php', + ], + ], + + 'multiple files marked as git modified, multiple files valid for scan' => [ + 'inputPaths' => $fakeFileList, + 'outputGitStaged' => [ + '.yamllint.yml', + 'autoload.php', + 'src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc.fixed', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js.fixed', + 'src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php', + ], + 'expectedOutput' => [ + $basedir.'/autoload.php', + $basedir.'/src', + $basedir.'/src/Standards', + $basedir.'/src/Standards/Squiz', + $basedir.'/src/Standards/Squiz/Sniffs', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace', + $basedir.'/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php', + $basedir.'/src/Standards/Squiz/Tests', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.inc', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.js', + $basedir.'/src/Standards/Squiz/Tests/WhiteSpace/OperatorSpacingUnitTest.php', + ], + ], + ]; + + return $testCases; + + }//end dataAcceptOnlyGitStaged() + + + /** + * Test filtering a file list for excluded paths. + * + * @param string $cmd Command to run. + * @param array $expected Expected return value. + * + * @dataProvider dataExecAlwaysReturnsArray + * + * @return void + */ + public function testExecAlwaysReturnsArray($cmd, $expected) + { + $fakeDI = new RecursiveArrayIterator(self::getFakeFileList()); + $filter = new GitStaged($fakeDI, '/', self::$config, self::$ruleset); + + $reflMethod = new ReflectionMethod($filter, 'exec'); + $reflMethod->setAccessible(true); + $result = $reflMethod->invoke($filter, $cmd); + + $this->assertSame($expected, $result); + + }//end testExecAlwaysReturnsArray() + + + /** + * Data provider. + * + * @see testExecAlwaysReturnsArray + * + * {@internal Missing: test with a command which yields a `false` return value. + * JRF: I've not managed to find a command which does so, let alone one, which then + * doesn't have side-effects of uncatchable output while running the tests.} + * + * @return array>> + */ + public static function dataExecAlwaysReturnsArray() + { + return [ + 'valid command which won\'t have any output unless files in the bin dir have been modified & staged' => [ + // Largely using the command used in the filter, but only checking the bin dir. + // This should prevent the test unexpectedly failing during local development (in most cases). + 'cmd' => 'git diff --cached --name-only -- '.escapeshellarg(self::getBaseDir().'/bin'), + 'expected' => [], + ], + 'valid command which will have output' => [ + 'cmd' => 'git ls-files --exclude-standard -- '.escapeshellarg(self::getBaseDir().'/bin'), + 'expected' => [ + 'bin/phpcbf', + 'bin/phpcbf.bat', + 'bin/phpcs', + 'bin/phpcs.bat', + ], + ], + ]; + + }//end dataExecAlwaysReturnsArray() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/ExplainTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/ExplainTest.php new file mode 100644 index 0000000..065a73c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/ExplainTest.php @@ -0,0 +1,60 @@ + + * @copyright 2023 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Ruleset; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; + +/** + * Test the Ruleset::explain() function. + * + * @covers \PHP_CodeSniffer\Ruleset::explain + */ +class ExplainTest extends TestCase +{ + + + /** + * Test the output of the "explain" command. + * + * @return void + */ + public function testExplain() + { + // Set up the ruleset. + $config = new Config(['--standard=PSR1', '-e']); + $ruleset = new Ruleset($config); + + $expected = PHP_EOL; + $expected .= 'The PSR1 standard contains 8 sniffs'.PHP_EOL.PHP_EOL; + $expected .= 'Generic (4 sniffs)'.PHP_EOL; + $expected .= '------------------'.PHP_EOL; + $expected .= ' Generic.Files.ByteOrderMark'.PHP_EOL; + $expected .= ' Generic.NamingConventions.UpperCaseConstantName'.PHP_EOL; + $expected .= ' Generic.PHP.DisallowAlternativePHPTags'.PHP_EOL; + $expected .= ' Generic.PHP.DisallowShortOpenTag'.PHP_EOL.PHP_EOL; + $expected .= 'PSR1 (3 sniffs)'.PHP_EOL; + $expected .= '---------------'.PHP_EOL; + $expected .= ' PSR1.Classes.ClassDeclaration'.PHP_EOL; + $expected .= ' PSR1.Files.SideEffects'.PHP_EOL; + $expected .= ' PSR1.Methods.CamelCapsMethodName'.PHP_EOL.PHP_EOL; + $expected .= 'Squiz (1 sniff)'.PHP_EOL; + $expected .= '---------------'.PHP_EOL; + $expected .= ' Squiz.Classes.ValidClassName'.PHP_EOL; + + $this->expectOutputString($expected); + + $ruleset->explain(); + + }//end testExplain() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedAsDeclaredSniff.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedAsDeclaredSniff.php new file mode 100644 index 0000000..7eeed21 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedAsDeclaredSniff.php @@ -0,0 +1,28 @@ +magic[$name] = $value; + } + + public function __get($name) + { + if (isset($this->magic[$name])) { + return $this->magic[$name]; + } + + return null; + } + + public function register() + { + return [T_WHITESPACE]; + } + + public function process(File $phpcsFile, $stackPtr) + { + // Do something. + } +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedViaStdClassSniff.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedViaStdClassSniff.php new file mode 100644 index 0000000..6ffffad --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/Fixtures/Sniffs/Category/SetPropertyAllowedViaStdClassSniff.php @@ -0,0 +1,26 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Ruleset; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; + +/** + * Tests for the \PHP_CodeSniffer\Ruleset class using a Linux-style absolute path to include a sniff. + * + * @covers \PHP_CodeSniffer\Ruleset + */ +class RuleInclusionAbsoluteLinuxTest extends TestCase +{ + + /** + * The Ruleset object. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected $ruleset; + + /** + * Path to the ruleset file. + * + * @var string + */ + private $standard = ''; + + /** + * The original content of the ruleset. + * + * @var string + */ + private $contents = ''; + + + /** + * Initialize the config and ruleset objects. + * + * @before + * + * @return void + */ + public function initializeConfigAndRuleset() + { + $this->standard = __DIR__.'/'.basename(__FILE__, '.php').'.xml'; + $repoRootDir = dirname(dirname(dirname(__DIR__))); + + // On-the-fly adjust the ruleset test file to be able to test sniffs included with absolute paths. + $contents = file_get_contents($this->standard); + $this->contents = $contents; + + $newPath = $repoRootDir; + if (DIRECTORY_SEPARATOR === '\\') { + $newPath = str_replace('\\', '/', $repoRootDir); + } + + $adjusted = str_replace('%path_slash_forward%', $newPath, $contents); + + if (file_put_contents($this->standard, $adjusted) === false) { + $this->markTestSkipped('On the fly ruleset adjustment failed'); + } + + // Initialize the config and ruleset objects for the test. + $config = new Config(["--standard={$this->standard}"]); + $this->ruleset = new Ruleset($config); + + }//end initializeConfigAndRuleset() + + + /** + * Reset ruleset file. + * + * @after + * + * @return void + */ + public function resetRuleset() + { + file_put_contents($this->standard, $this->contents); + + }//end resetRuleset() + + + /** + * Test that sniffs registed with a Linux absolute path are correctly recognized and that + * properties are correctly set for them. + * + * @return void + */ + public function testLinuxStylePathRuleInclusion() + { + // Test that the sniff is correctly registered. + $this->assertCount(1, $this->ruleset->sniffCodes); + $this->assertArrayHasKey('Generic.Formatting.SpaceAfterNot', $this->ruleset->sniffCodes); + $this->assertSame( + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterNotSniff', + $this->ruleset->sniffCodes['Generic.Formatting.SpaceAfterNot'] + ); + + // Test that the sniff properties are correctly set. + $this->assertSame( + '10', + $this->ruleset->sniffs['PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterNotSniff']->spacing + ); + + }//end testLinuxStylePathRuleInclusion() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteLinuxTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteLinuxTest.xml new file mode 100644 index 0000000..2978cef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteLinuxTest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.php new file mode 100644 index 0000000..629668c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.php @@ -0,0 +1,120 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Ruleset; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; + +/** + * Tests for the \PHP_CodeSniffer\Ruleset class using a Windows-style absolute path to include a sniff. + * + * @covers \PHP_CodeSniffer\Ruleset + */ +class RuleInclusionAbsoluteWindowsTest extends TestCase +{ + + /** + * The Ruleset object. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected $ruleset; + + /** + * Path to the ruleset file. + * + * @var string + */ + private $standard = ''; + + /** + * The original content of the ruleset. + * + * @var string + */ + private $contents = ''; + + + /** + * Initialize the config and ruleset objects. + * + * @before + * + * @return void + */ + public function initializeConfigAndRuleset() + { + if (DIRECTORY_SEPARATOR === '/') { + $this->markTestSkipped('Windows specific test'); + } + + $this->standard = __DIR__.'/'.basename(__FILE__, '.php').'.xml'; + $repoRootDir = dirname(dirname(dirname(__DIR__))); + + // On-the-fly adjust the ruleset test file to be able to test sniffs included with absolute paths. + $contents = file_get_contents($this->standard); + $this->contents = $contents; + + $adjusted = str_replace('%path_slash_back%', $repoRootDir, $contents); + + if (file_put_contents($this->standard, $adjusted) === false) { + $this->markTestSkipped('On the fly ruleset adjustment failed'); + } + + // Initialize the config and ruleset objects for the test. + $config = new Config(["--standard={$this->standard}"]); + $this->ruleset = new Ruleset($config); + + }//end initializeConfigAndRuleset() + + + /** + * Reset ruleset file. + * + * @after + * + * @return void + */ + public function resetRuleset() + { + if (DIRECTORY_SEPARATOR !== '/') { + file_put_contents($this->standard, $this->contents); + } + + }//end resetRuleset() + + + /** + * Test that sniffs registed with a Windows absolute path are correctly recognized and that + * properties are correctly set for them. + * + * @return void + */ + public function testWindowsStylePathRuleInclusion() + { + // Test that the sniff is correctly registered. + $this->assertCount(1, $this->ruleset->sniffCodes); + $this->assertArrayHasKey('Generic.Formatting.SpaceAfterCast', $this->ruleset->sniffCodes); + $this->assertSame( + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterCastSniff', + $this->ruleset->sniffCodes['Generic.Formatting.SpaceAfterCast'] + ); + + // Test that the sniff property is correctly set. + $this->assertSame( + '10', + $this->ruleset->sniffs['PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\SpaceAfterCastSniff']->spacing + ); + + }//end testWindowsStylePathRuleInclusion() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.xml new file mode 100644 index 0000000..e92c688 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionAbsoluteWindowsTest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest-include.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest-include.xml new file mode 100644 index 0000000..d95af20 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest-include.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.php new file mode 100644 index 0000000..df4a022 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.php @@ -0,0 +1,478 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Ruleset; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; +use ReflectionObject; + +/** + * Tests for the \PHP_CodeSniffer\Ruleset class. + * + * @covers \PHP_CodeSniffer\Ruleset + */ +class RuleInclusionTest extends TestCase +{ + + /** + * The Ruleset object. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected static $ruleset; + + /** + * Path to the ruleset file. + * + * @var string + */ + private static $standard = ''; + + /** + * The original content of the ruleset. + * + * @var string + */ + private static $contents = ''; + + + /** + * Initialize the config and ruleset objects based on the `RuleInclusionTest.xml` ruleset file. + * + * @beforeClass + * + * @return void + */ + public static function initializeConfigAndRuleset() + { + $standard = __DIR__.'/'.basename(__FILE__, '.php').'.xml'; + self::$standard = $standard; + + // On-the-fly adjust the ruleset test file to be able to test + // sniffs included with relative paths. + $contents = file_get_contents($standard); + self::$contents = $contents; + + $repoRootDir = basename(dirname(dirname(dirname(__DIR__)))); + + $newPath = $repoRootDir; + if (DIRECTORY_SEPARATOR === '\\') { + $newPath = str_replace('\\', '/', $repoRootDir); + } + + $adjusted = str_replace('%path_root_dir%', $newPath, $contents); + + if (file_put_contents($standard, $adjusted) === false) { + self::markTestSkipped('On the fly ruleset adjustment failed'); + } + + $config = new Config(["--standard=$standard"]); + self::$ruleset = new Ruleset($config); + + }//end initializeConfigAndRuleset() + + + /** + * Reset ruleset file. + * + * @after + * + * @return void + */ + public function resetRuleset() + { + file_put_contents(self::$standard, self::$contents); + + }//end resetRuleset() + + + /** + * Test that sniffs are registered. + * + * @return void + */ + public function testHasSniffCodes() + { + $this->assertCount(48, self::$ruleset->sniffCodes); + + }//end testHasSniffCodes() + + + /** + * Test that sniffs are correctly registered, independently of the syntax used to include the sniff. + * + * @param string $key Expected array key. + * @param string $value Expected array value. + * + * @dataProvider dataRegisteredSniffCodes + * + * @return void + */ + public function testRegisteredSniffCodes($key, $value) + { + $this->assertArrayHasKey($key, self::$ruleset->sniffCodes); + $this->assertSame($value, self::$ruleset->sniffCodes[$key]); + + }//end testRegisteredSniffCodes() + + + /** + * Data provider. + * + * @see self::testRegisteredSniffCodes() + * + * @return array + */ + public function dataRegisteredSniffCodes() + { + return [ + [ + 'PSR2.Classes.ClassDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff', + ], + [ + 'PSR2.Classes.PropertyDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\PropertyDeclarationSniff', + ], + [ + 'PSR2.ControlStructures.ControlStructureSpacing', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ControlStructureSpacingSniff', + ], + [ + 'PSR2.ControlStructures.ElseIfDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\ElseIfDeclarationSniff', + ], + [ + 'PSR2.ControlStructures.SwitchDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\SwitchDeclarationSniff', + ], + [ + 'PSR2.Files.ClosingTag', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Files\ClosingTagSniff', + ], + [ + 'PSR2.Files.EndFileNewline', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Files\EndFileNewlineSniff', + ], + [ + 'PSR2.Methods.FunctionCallSignature', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionCallSignatureSniff', + ], + [ + 'PSR2.Methods.FunctionClosingBrace', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionClosingBraceSniff', + ], + [ + 'PSR2.Methods.MethodDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\MethodDeclarationSniff', + ], + [ + 'PSR2.Namespaces.NamespaceDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces\NamespaceDeclarationSniff', + ], + [ + 'PSR2.Namespaces.UseDeclaration', + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Namespaces\UseDeclarationSniff', + ], + [ + 'PSR1.Classes.ClassDeclaration', + 'PHP_CodeSniffer\Standards\PSR1\Sniffs\Classes\ClassDeclarationSniff', + ], + [ + 'PSR1.Files.SideEffects', + 'PHP_CodeSniffer\Standards\PSR1\Sniffs\Files\SideEffectsSniff', + ], + [ + 'PSR1.Methods.CamelCapsMethodName', + 'PHP_CodeSniffer\Standards\PSR1\Sniffs\Methods\CamelCapsMethodNameSniff', + ], + [ + 'Generic.PHP.DisallowAlternativePHPTags', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DisallowAlternativePHPTagsSniff', + ], + [ + 'Generic.PHP.DisallowShortOpenTag', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\DisallowShortOpenTagSniff', + ], + [ + 'Generic.Files.ByteOrderMark', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Files\ByteOrderMarkSniff', + ], + [ + 'Squiz.Classes.ValidClassName', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ValidClassNameSniff', + ], + [ + 'Generic.NamingConventions.UpperCaseConstantName', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\UpperCaseConstantNameSniff', + ], + [ + 'Generic.Files.LineEndings', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineEndingsSniff', + ], + [ + 'Generic.Files.LineLength', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff', + ], + [ + 'Squiz.WhiteSpace.SuperfluousWhitespace', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\SuperfluousWhitespaceSniff', + ], + [ + 'Generic.Formatting.DisallowMultipleStatements', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting\DisallowMultipleStatementsSniff', + ], + [ + 'Generic.WhiteSpace.ScopeIndent', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff', + ], + [ + 'Generic.WhiteSpace.DisallowTabIndent', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\DisallowTabIndentSniff', + ], + [ + 'Generic.PHP.LowerCaseKeyword', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\LowerCaseKeywordSniff', + ], + [ + 'Generic.PHP.LowerCaseConstant', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\LowerCaseConstantSniff', + ], + [ + 'Squiz.Scope.MethodScope', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope\MethodScopeSniff', + ], + [ + 'Squiz.WhiteSpace.ScopeKeywordSpacing', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeKeywordSpacingSniff', + ], + [ + 'Squiz.Functions.FunctionDeclaration', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationSniff', + ], + [ + 'Squiz.Functions.LowercaseFunctionKeywords', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\LowercaseFunctionKeywordsSniff', + ], + [ + 'Squiz.Functions.FunctionDeclarationArgumentSpacing', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationArgumentSpacingSniff', + ], + [ + 'PEAR.Functions.ValidDefaultValue', + 'PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\ValidDefaultValueSniff', + ], + [ + 'Squiz.Functions.MultiLineFunctionDeclaration', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff', + ], + [ + 'Generic.Functions.FunctionCallArgumentSpacing', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Functions\FunctionCallArgumentSpacingSniff', + ], + [ + 'Squiz.ControlStructures.ControlSignature', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff', + ], + [ + 'Squiz.WhiteSpace.ControlStructureSpacing', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff', + ], + [ + 'Squiz.WhiteSpace.ScopeClosingBrace', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff', + ], + [ + 'Squiz.ControlStructures.ForEachLoopDeclaration', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForEachLoopDeclarationSniff', + ], + [ + 'Squiz.ControlStructures.ForLoopDeclaration', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForLoopDeclarationSniff', + ], + [ + 'Squiz.ControlStructures.LowercaseDeclaration', + 'PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\LowercaseDeclarationSniff', + ], + [ + 'Generic.ControlStructures.InlineControlStructure', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\ControlStructures\InlineControlStructureSniff', + ], + [ + 'PSR12.Operators.OperatorSpacing', + 'PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff', + ], + [ + 'Generic.Arrays.ArrayIndent', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\ArrayIndentSniff', + ], + [ + 'Generic.Metrics.CyclomaticComplexity', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics\CyclomaticComplexitySniff', + ], + [ + 'Generic.NamingConventions.CamelCapsFunctionName', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff', + ], + [ + 'Generic.Metrics.NestingLevel', + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics\NestingLevelSniff', + ], + ]; + + }//end dataRegisteredSniffCodes() + + + /** + * Test that setting properties for standards, categories, sniffs works for all supported rule + * inclusion methods. + * + * @param string $sniffClass The name of the sniff class. + * @param string $propertyName The name of the changed property. + * @param mixed $expectedValue The value expected for the property. + * + * @dataProvider dataSettingProperties + * + * @return void + */ + public function testSettingProperties($sniffClass, $propertyName, $expectedValue) + { + $this->assertArrayHasKey($sniffClass, self::$ruleset->sniffs); + + $hasProperty = (new ReflectionObject(self::$ruleset->sniffs[$sniffClass]))->hasProperty($propertyName); + $errorMsg = sprintf('Property %s does not exist on sniff class %s', $propertyName, $sniffClass); + $this->assertTrue($hasProperty, $errorMsg); + + $actualValue = self::$ruleset->sniffs[$sniffClass]->$propertyName; + $this->assertSame($expectedValue, $actualValue); + + }//end testSettingProperties() + + + /** + * Data provider. + * + * @see self::testSettingProperties() + * + * @return array + */ + public function dataSettingProperties() + { + return [ + 'Set property for complete standard: PSR2 ClassDeclaration' => [ + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff', + 'indent', + '20', + ], + 'Set property for complete standard: PSR2 SwitchDeclaration' => [ + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\ControlStructures\SwitchDeclarationSniff', + 'indent', + '20', + ], + 'Set property for complete standard: PSR2 FunctionCallSignature' => [ + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionCallSignatureSniff', + 'indent', + '20', + ], + 'Set property for complete category: PSR12 OperatorSpacing' => [ + 'PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff', + 'ignoreSpacingBeforeAssignments', + false, + ], + 'Set property for individual sniff: Generic ArrayIndent' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays\ArrayIndentSniff', + 'indent', + '2', + ], + 'Set property for individual sniff using sniff file inclusion: Generic LineLength' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff', + 'lineLimit', + '10', + ], + 'Set property for individual sniff using sniff file inclusion: CamelCapsFunctionName' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions\CamelCapsFunctionNameSniff', + 'strict', + false, + ], + 'Set property for individual sniff via included ruleset: NestingLevel - nestingLevel' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics\NestingLevelSniff', + 'nestingLevel', + '2', + ], + 'Set property for all sniffs in an included ruleset: NestingLevel - absoluteNestingLevel' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics\NestingLevelSniff', + 'absoluteNestingLevel', + true, + ], + + // Testing that setting a property at error code level does *not* work. + 'Set property for error code will not change the sniff property value: CyclomaticComplexity' => [ + 'PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics\CyclomaticComplexitySniff', + 'complexity', + 10, + ], + ]; + + }//end dataSettingProperties() + + + /** + * Test that setting properties for standards, categories on sniffs which don't support the property will + * silently ignore the property and not set it. + * + * @param string $sniffClass The name of the sniff class. + * @param string $propertyName The name of the property which should not be set. + * + * @dataProvider dataSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails + * + * @return void + */ + public function testSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails($sniffClass, $propertyName) + { + $this->assertArrayHasKey($sniffClass, self::$ruleset->sniffs, 'Sniff class '.$sniffClass.' not listed in registered sniffs'); + + $sniffObject = self::$ruleset->sniffs[$sniffClass]; + + $hasProperty = (new ReflectionObject(self::$ruleset->sniffs[$sniffClass]))->hasProperty($propertyName); + $errorMsg = sprintf('Property %s registered for sniff %s which does not support it', $propertyName, $sniffClass); + $this->assertFalse($hasProperty, $errorMsg); + + }//end testSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails() + + + /** + * Data provider. + * + * @see self::testSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails() + * + * @return array + */ + public function dataSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails() + { + return [ + 'Set property for complete standard: PSR2 ClassDeclaration' => [ + 'PHP_CodeSniffer\Standards\PSR1\Sniffs\Classes\ClassDeclarationSniff', + 'setforallsniffs', + ], + 'Set property for complete standard: PSR2 FunctionCallSignature' => [ + 'PHP_CodeSniffer\Standards\PSR2\Sniffs\Methods\FunctionCallSignatureSniff', + 'setforallsniffs', + ], + 'Set property for complete category: PSR12 OperatorSpacing' => [ + 'PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff', + 'setforallincategory', + ], + ]; + + }//end dataSettingInvalidPropertiesOnStandardsAndCategoriesSilentlyFails() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.xml new file mode 100644 index 0000000..e1812bb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/RuleInclusionTest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedAsDeclaredTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedAsDeclaredTest.xml new file mode 100644 index 0000000..70859ba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedAsDeclaredTest.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaMagicMethodTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaMagicMethodTest.xml new file mode 100644 index 0000000..65e2255 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaMagicMethodTest.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaStdClassTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaStdClassTest.xml new file mode 100644 index 0000000..ba094db --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAllowedViaStdClassTest.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAppliesPropertyToMultipleSniffsInCategoryTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAppliesPropertyToMultipleSniffsInCategoryTest.xml new file mode 100644 index 0000000..7c4ca4f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyAppliesPropertyToMultipleSniffsInCategoryTest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategoryTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategoryTest.xml new file mode 100644 index 0000000..979b48f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategoryTest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandardTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandardTest.xml new file mode 100644 index 0000000..48a36a8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandardTest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyNotAllowedViaAttributeTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyNotAllowedViaAttributeTest.xml new file mode 100644 index 0000000..e411520 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyNotAllowedViaAttributeTest.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyThrowsErrorOnInvalidPropertyTest.xml b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyThrowsErrorOnInvalidPropertyTest.xml new file mode 100644 index 0000000..5dca1a0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetPropertyThrowsErrorOnInvalidPropertyTest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetSniffPropertyTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetSniffPropertyTest.php new file mode 100644 index 0000000..1b3d955 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Ruleset/SetSniffPropertyTest.php @@ -0,0 +1,399 @@ + + * @copyright 2022 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Ruleset; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHPUnit\Framework\TestCase; +use ReflectionObject; + +/** + * These tests specifically focus on the changes made to work around the PHP 8.2 dynamic properties deprecation. + * + * @covers \PHP_CodeSniffer\Ruleset::setSniffProperty + */ +class SetSniffPropertyTest extends TestCase +{ + + + /** + * Test that setting a property via the ruleset works in all situations which allow for it. + * + * @param string $name Name of the test. Used for the sniff name, the ruleset file name etc. + * + * @dataProvider dataSniffPropertiesGetSetWhenAllowed + * + * @return void + */ + public function testSniffPropertiesGetSetWhenAllowed($name) + { + $sniffCode = "Fixtures.Category.{$name}"; + $sniffClass = 'Fixtures\Sniffs\Category\\'.$name.'Sniff'; + $properties = [ + 'arbitrarystring' => 'arbitraryvalue', + 'arbitraryarray' => [ + 'mykey' => 'myvalue', + 'otherkey' => 'othervalue', + ], + ]; + + // Set up the ruleset. + $standard = __DIR__."/{$name}Test.xml"; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + // Verify that the sniff has been registered. + $this->assertGreaterThan(0, count($ruleset->sniffCodes), 'No sniff codes registered'); + + // Verify that our target sniff has been registered. + $this->assertArrayHasKey($sniffCode, $ruleset->sniffCodes, 'Target sniff not registered'); + $this->assertSame($sniffClass, $ruleset->sniffCodes[$sniffCode], 'Target sniff not registered with the correct class'); + + // Test that the property as declared in the ruleset has been set on the sniff. + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class not listed in registered sniffs'); + + $sniffObject = $ruleset->sniffs[$sniffClass]; + foreach ($properties as $name => $expectedValue) { + $this->assertSame($expectedValue, $sniffObject->$name, 'Property value not set to expected value'); + } + + }//end testSniffPropertiesGetSetWhenAllowed() + + + /** + * Data provider. + * + * @see self::testSniffPropertiesGetSetWhenAllowed() + * + * @return array + */ + public function dataSniffPropertiesGetSetWhenAllowed() + { + return [ + 'Property allowed as explicitly declared' => ['SetPropertyAllowedAsDeclared'], + 'Property allowed as sniff extends stdClass' => ['SetPropertyAllowedViaStdClass'], + 'Property allowed as sniff has magic __set() method' => ['SetPropertyAllowedViaMagicMethod'], + ]; + + }//end dataSniffPropertiesGetSetWhenAllowed() + + + /** + * Test that setting a property for a category will apply it correctly to those sniffs which support the + * property, but won't apply it to sniffs which don't. + * + * Note: this test intentionally uses the `PEAR.Functions` category as two sniffs in that category + * have a public property with the same name (`indent`) and one sniff doesn't, which makes it a great + * test case for this. + * + * @return void + */ + public function testSetPropertyAppliesPropertyToMultipleSniffsInCategory() + { + $propertyName = 'indent'; + $expectedValue = '10'; + + // Set up the ruleset. + $standard = __DIR__.'/SetPropertyAppliesPropertyToMultipleSniffsInCategoryTest.xml'; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + // Test that the two sniffs which support the property have received the value. + $sniffClass = 'PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionCallSignatureSniff'; + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class '.$sniffClass.' not listed in registered sniffs'); + $sniffObject = $ruleset->sniffs[$sniffClass]; + $this->assertSame($expectedValue, $sniffObject->$propertyName, 'Property value not set to expected value for '.$sniffClass); + + $sniffClass = 'PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionDeclarationSniff'; + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class '.$sniffClass.' not listed in registered sniffs'); + $sniffObject = $ruleset->sniffs[$sniffClass]; + $this->assertSame($expectedValue, $sniffObject->$propertyName, 'Property value not set to expected value for '.$sniffClass); + + // Test that the property doesn't get set for the one sniff which doesn't support the property. + $sniffClass = 'PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\ValidDefaultValueSniff'; + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class '.$sniffClass.' not listed in registered sniffs'); + + $hasProperty = (new ReflectionObject($ruleset->sniffs[$sniffClass]))->hasProperty($propertyName); + $errorMsg = sprintf('Property %s registered for sniff %s which does not support it', $propertyName, $sniffClass); + $this->assertFalse($hasProperty, $errorMsg); + + }//end testSetPropertyAppliesPropertyToMultipleSniffsInCategory() + + + /** + * Test that attempting to set a non-existent property directly on a sniff will throw an error + * when the sniff does not explicitly declare the property, extends stdClass or has magic methods. + * + * @return void + */ + public function testSetPropertyThrowsErrorOnInvalidProperty() + { + $exceptionClass = 'PHP_CodeSniffer\Exceptions\RuntimeException'; + $exceptionMsg = 'Ruleset invalid. Property "indentation" does not exist on sniff Generic.Arrays.ArrayIndent'; + if (method_exists($this, 'expectException') === true) { + $this->expectException($exceptionClass); + $this->expectExceptionMessage($exceptionMsg); + } else { + // PHPUnit < 5.2.0. + $this->setExpectedException($exceptionClass, $exceptionMsg); + } + + // Set up the ruleset. + $standard = __DIR__.'/SetPropertyThrowsErrorOnInvalidPropertyTest.xml'; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + }//end testSetPropertyThrowsErrorOnInvalidProperty() + + + /** + * Test that attempting to set a non-existent property directly on a sniff will throw an error + * when the sniff does not explicitly declare the property, extends stdClass or has magic methods, + * even though the sniff has the PHP 8.2 `#[AllowDynamicProperties]` attribute set. + * + * @return void + */ + public function testSetPropertyThrowsErrorWhenPropertyOnlyAllowedViaAttribute() + { + $exceptionClass = 'PHP_CodeSniffer\Exceptions\RuntimeException'; + $exceptionMsg = 'Ruleset invalid. Property "arbitrarystring" does not exist on sniff Fixtures.Category.SetPropertyNotAllowedViaAttribute'; + if (method_exists($this, 'expectException') === true) { + $this->expectException($exceptionClass); + $this->expectExceptionMessage($exceptionMsg); + } else { + // PHPUnit < 5.2.0. + $this->setExpectedException($exceptionClass, $exceptionMsg); + } + + // Set up the ruleset. + $standard = __DIR__.'/SetPropertyNotAllowedViaAttributeTest.xml'; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + }//end testSetPropertyThrowsErrorWhenPropertyOnlyAllowedViaAttribute() + + + /** + * Test that attempting to set a non-existent property on a sniff when the property directive is + * for the whole standard, does not yield an error. + * + * @doesNotPerformAssertions + * + * @return void + */ + public function testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandard() + { + // Set up the ruleset. + $standard = __DIR__.'/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandardTest.xml'; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + }//end testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForStandard() + + + /** + * Test that attempting to set a non-existent property on a sniff when the property directive is + * for a whole category, does not yield an error. + * + * @doesNotPerformAssertions + * + * @return void + */ + public function testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategory() + { + // Set up the ruleset. + $standard = __DIR__.'/SetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategoryTest.xml'; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + }//end testSetPropertyDoesNotThrowErrorOnInvalidPropertyWhenSetForCategory() + + + /** + * Test that setting a property via a direct call to the Ruleset::setSniffProperty() method + * sets the property correctly when using the new $settings array format. + * + * @return void + */ + public function testDirectCallWithNewArrayFormatSetsProperty() + { + $name = 'SetPropertyAllowedAsDeclared'; + $sniffCode = "Fixtures.Category.{$name}"; + $sniffClass = 'Fixtures\Sniffs\Category\\'.$name.'Sniff'; + + // Set up the ruleset. + $standard = __DIR__."/{$name}Test.xml"; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + $propertyName = 'arbitrarystring'; + $propertyValue = 'new value'; + + $ruleset->setSniffProperty( + $sniffClass, + $propertyName, + [ + 'scope' => 'sniff', + 'value' => $propertyValue, + ] + ); + + // Verify that the sniff has been registered. + $this->assertGreaterThan(0, count($ruleset->sniffCodes), 'No sniff codes registered'); + + // Verify that our target sniff has been registered. + $this->assertArrayHasKey($sniffCode, $ruleset->sniffCodes, 'Target sniff not registered'); + $this->assertSame($sniffClass, $ruleset->sniffCodes[$sniffCode], 'Target sniff not registered with the correct class'); + + // Test that the property as declared in the ruleset has been set on the sniff. + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class not listed in registered sniffs'); + + $sniffObject = $ruleset->sniffs[$sniffClass]; + $this->assertSame($propertyValue, $sniffObject->$propertyName, 'Property value not set to expected value'); + + }//end testDirectCallWithNewArrayFormatSetsProperty() + + + /** + * Test that setting a property via a direct call to the Ruleset::setSniffProperty() method + * sets the property correctly when using the old $settings array format. + * + * Tested by silencing the deprecation notice as otherwise the test would fail on the deprecation notice. + * + * @param mixed $propertyValue Value for the property to set. + * + * @dataProvider dataDirectCallWithOldArrayFormatSetsProperty + * + * @return void + */ + public function testDirectCallWithOldArrayFormatSetsProperty($propertyValue) + { + $name = 'SetPropertyAllowedAsDeclared'; + $sniffCode = "Fixtures.Category.{$name}"; + $sniffClass = 'Fixtures\Sniffs\Category\\'.$name.'Sniff'; + + // Set up the ruleset. + $standard = __DIR__."/{$name}Test.xml"; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + $propertyName = 'arbitrarystring'; + + @$ruleset->setSniffProperty( + $sniffClass, + $propertyName, + $propertyValue + ); + + // Verify that the sniff has been registered. + $this->assertGreaterThan(0, count($ruleset->sniffCodes), 'No sniff codes registered'); + + // Verify that our target sniff has been registered. + $this->assertArrayHasKey($sniffCode, $ruleset->sniffCodes, 'Target sniff not registered'); + $this->assertSame($sniffClass, $ruleset->sniffCodes[$sniffCode], 'Target sniff not registered with the correct class'); + + // Test that the property as declared in the ruleset has been set on the sniff. + $this->assertArrayHasKey($sniffClass, $ruleset->sniffs, 'Sniff class not listed in registered sniffs'); + + $sniffObject = $ruleset->sniffs[$sniffClass]; + $this->assertSame($propertyValue, $sniffObject->$propertyName, 'Property value not set to expected value'); + + }//end testDirectCallWithOldArrayFormatSetsProperty() + + + /** + * Data provider. + * + * @see self::testDirectCallWithOldArrayFormatSetsProperty() + * + * @return array + */ + public function dataDirectCallWithOldArrayFormatSetsProperty() + { + return [ + 'Property value is not an array (boolean)' => [false], + 'Property value is not an array (string)' => ['a string'], + 'Property value is an empty array' => [[]], + 'Property value is an array without keys' => [ + [ + 'value', + false, + ], + ], + 'Property value is an array without the "scope" or "value" keys' => [ + [ + 'key1' => 'value', + 'key2' => false, + ], + ], + 'Property value is an array without the "scope" key' => [ + [ + 'key1' => 'value', + 'value' => true, + ], + ], + 'Property value is an array without the "value" key' => [ + [ + 'scope' => 'value', + 'key2' => 1234, + ], + ], + ]; + + }//end dataDirectCallWithOldArrayFormatSetsProperty() + + + /** + * Test that setting a property via a direct call to the Ruleset::setSniffProperty() method + * throws a deprecation notice when using the old $settings array format. + * + * Note: as PHPUnit stops as soon as it sees the deprecation notice, the setting of the property + * value is not tested here. + * + * @return void + */ + public function testDirectCallWithOldArrayFormatThrowsDeprecationNotice() + { + $exceptionClass = 'PHPUnit\Framework\Error\Deprecated'; + if (class_exists($exceptionClass) === false) { + $exceptionClass = 'PHPUnit_Framework_Error_Deprecated'; + } + + $exceptionMsg = 'the format of the $settings parameter has changed from (mixed) $value to array(\'scope\' => \'sniff|standard\', \'value\' => $value). Please update your integration code. See PR #3629 for more information.'; + + if (method_exists($this, 'expectException') === true) { + $this->expectException($exceptionClass); + $this->expectExceptionMessage($exceptionMsg); + } else { + // PHPUnit < 5.2.0. + $this->setExpectedException($exceptionClass, $exceptionMsg); + } + + $name = 'SetPropertyAllowedAsDeclared'; + $sniffCode = "Fixtures.Category.{$name}"; + $sniffClass = 'Fixtures\Sniffs\Category\\'.$name.'Sniff'; + + // Set up the ruleset. + $standard = __DIR__."/{$name}Test.xml"; + $config = new Config(["--standard=$standard"]); + $ruleset = new Ruleset($config); + + $propertyName = 'arbitrarystring'; + + $ruleset->setSniffProperty( + $sniffClass, + 'arbitrarystring', + ['key' => 'value'] + ); + + }//end testDirectCallWithOldArrayFormatThrowsDeprecationNotice() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.inc new file mode 100644 index 0000000..4882295 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.inc @@ -0,0 +1,51 @@ +1,'2'=>2,'3'=>3]; + +/* testMissingKeys */ +$foo = ['1'=>1,2,'3'=>3]; + +/* testMultiTokenKeys */ +$paths = array( + Init::ROOT_DIR.'/a' => 'a', + Init::ROOT_DIR.'/b' => 'b', +); + +/* testMissingKeysCoalesceTernary */ +return [ + $a => static function () { return [1,2,3]; }, + $b ?? $c, + $d ? [$e] : [$f], +]; + +/* testTernaryValues */ +$foo = [ + '1' => $row['status'] === 'rejected' + ? self::REJECTED_CODE + : self::VERIFIED_CODE, + '2' => in_array($row['status'], array('notverified', 'unverified'), true) + ? self::STATUS_PENDING + : self::STATUS_VERIFIED, + '3' => strtotime($row['date']), +]; + +/* testHeredocValues */ +$foo = array( + << '1', + 2 => fn ($x) => yield 'a' => $x, + 3 => '3', +); diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.php new file mode 100644 index 0000000..cf8a231 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTest.php @@ -0,0 +1,297 @@ + + * @copyright 2006-2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Sniffs; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Tests for the \PHP_CodeSniffer\Sniffs\AbstractArraySniff. + * + * @covers \PHP_CodeSniffer\Sniffs\AbstractArraySniff + */ +class AbstractArraySniffTest extends AbstractMethodUnitTest +{ + + /** + * The sniff objects we are testing. + * + * This extends the \PHP_CodeSniffer\Sniffs\AbstractArraySniff class to make the + * internal workings of the sniff observable. + * + * @var \PHP_CodeSniffer\Sniffs\AbstractArraySniffTestable + */ + protected static $sniff; + + + /** + * Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file. + * + * The test case file for a unit test class has to be in the same directory + * directory and use the same file name as the test class, using the .inc extension. + * + * @beforeClass + * + * @return void + */ + public static function initializeFile() + { + self::$sniff = new AbstractArraySniffTestable(); + parent::initializeFile(); + + }//end initializeFile() + + + /** + * Test an array of simple values only. + * + * @return void + */ + public function testSimpleValues() + { + $token = $this->getTargetToken('/* testSimpleValues */', T_OPEN_SHORT_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => ['value_start' => ($token + 1)], + 1 => ['value_start' => ($token + 3)], + 2 => ['value_start' => ($token + 5)], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testSimpleValues() + + + /** + * Test an array of simple keys and values. + * + * @return void + */ + public function testSimpleKeyValues() + { + $token = $this->getTargetToken('/* testSimpleKeyValues */', T_OPEN_SHORT_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 1), + 'index_end' => ($token + 1), + 'arrow' => ($token + 2), + 'value_start' => ($token + 3), + ], + 1 => [ + 'index_start' => ($token + 5), + 'index_end' => ($token + 5), + 'arrow' => ($token + 6), + 'value_start' => ($token + 7), + ], + 2 => [ + 'index_start' => ($token + 9), + 'index_end' => ($token + 9), + 'arrow' => ($token + 10), + 'value_start' => ($token + 11), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testSimpleKeyValues() + + + /** + * Test an array of simple keys and values. + * + * @return void + */ + public function testMissingKeys() + { + $token = $this->getTargetToken('/* testMissingKeys */', T_OPEN_SHORT_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 1), + 'index_end' => ($token + 1), + 'arrow' => ($token + 2), + 'value_start' => ($token + 3), + ], + 1 => [ + 'value_start' => ($token + 5), + ], + 2 => [ + 'index_start' => ($token + 7), + 'index_end' => ($token + 7), + 'arrow' => ($token + 8), + 'value_start' => ($token + 9), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testMissingKeys() + + + /** + * Test an array with keys that span multiple tokens. + * + * @return void + */ + public function testMultiTokenKeys() + { + $token = $this->getTargetToken('/* testMultiTokenKeys */', T_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 4), + 'index_end' => ($token + 8), + 'arrow' => ($token + 10), + 'value_start' => ($token + 12), + ], + 1 => [ + 'index_start' => ($token + 16), + 'index_end' => ($token + 20), + 'arrow' => ($token + 22), + 'value_start' => ($token + 24), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testMultiTokenKeys() + + + /** + * Test an array of simple keys and values. + * + * @return void + */ + public function testMissingKeysCoalesceTernary() + { + $token = $this->getTargetToken('/* testMissingKeysCoalesceTernary */', T_OPEN_SHORT_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 3), + 'index_end' => ($token + 3), + 'arrow' => ($token + 5), + 'value_start' => ($token + 7), + ], + 1 => [ + 'value_start' => ($token + 31), + ], + 2 => [ + 'value_start' => ($token + 39), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testMissingKeysCoalesceTernary() + + + /** + * Test an array of ternary values. + * + * @return void + */ + public function testTernaryValues() + { + $token = $this->getTargetToken('/* testTernaryValues */', T_OPEN_SHORT_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 3), + 'index_end' => ($token + 3), + 'arrow' => ($token + 5), + 'value_start' => ($token + 7), + ], + 1 => [ + 'index_start' => ($token + 32), + 'index_end' => ($token + 32), + 'arrow' => ($token + 34), + 'value_start' => ($token + 36), + ], + 2 => [ + 'index_start' => ($token + 72), + 'index_end' => ($token + 72), + 'arrow' => ($token + 74), + 'value_start' => ($token + 76), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testTernaryValues() + + + /** + * Test an array of heredocs. + * + * @return void + */ + public function testHeredocValues() + { + $token = $this->getTargetToken('/* testHeredocValues */', T_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'value_start' => ($token + 4), + ], + 1 => [ + 'value_start' => ($token + 10), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testHeredocValues() + + + /** + * Test an array of with an arrow function as a value. + * + * @return void + */ + public function testArrowFunctionValue() + { + $token = $this->getTargetToken('/* testArrowFunctionValue */', T_ARRAY); + self::$sniff->process(self::$phpcsFile, $token); + + $expected = [ + 0 => [ + 'index_start' => ($token + 4), + 'index_end' => ($token + 4), + 'arrow' => ($token + 6), + 'value_start' => ($token + 8), + ], + 1 => [ + 'index_start' => ($token + 12), + 'index_end' => ($token + 12), + 'arrow' => ($token + 14), + 'value_start' => ($token + 16), + ], + 2 => [ + 'index_start' => ($token + 34), + 'index_end' => ($token + 34), + 'arrow' => ($token + 36), + 'value_start' => ($token + 38), + ], + ]; + + $this->assertSame($expected, self::$sniff->indicies); + + }//end testArrowFunctionValue() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTestable.php b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTestable.php new file mode 100644 index 0000000..751b01a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Sniffs/AbstractArraySniffTestable.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Sniffs; + +use PHP_CodeSniffer\Sniffs\AbstractArraySniff; + +class AbstractArraySniffTestable extends AbstractArraySniff +{ + + /** + * The array indicies that were found during processing. + * + * @var array + */ + public $indicies = []; + + + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + $this->indicies = $indices; + + }//end processSingleLineArray() + + + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + $this->indicies = $indices; + + }//end processMultiLineArray() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AnonClassParenthesisOwnerTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AnonClassParenthesisOwnerTest.inc new file mode 100644 index 0000000..5867691 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AnonClassParenthesisOwnerTest.inc @@ -0,0 +1,19 @@ + + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class AnonClassParenthesisOwnerTest extends AbstractMethodUnitTest +{ + + + /** + * Test that anonymous class tokens without parenthesis do not get assigned a parenthesis owner. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataAnonClassNoParentheses + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testAnonClassNoParentheses($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $anonClass = $this->getTargetToken($testMarker, T_ANON_CLASS); + $this->assertFalse(array_key_exists('parenthesis_owner', $tokens[$anonClass])); + $this->assertFalse(array_key_exists('parenthesis_opener', $tokens[$anonClass])); + $this->assertFalse(array_key_exists('parenthesis_closer', $tokens[$anonClass])); + + }//end testAnonClassNoParentheses() + + + /** + * Test that the next open/close parenthesis after an anonymous class without parenthesis + * do not get assigned the anonymous class as a parenthesis owner. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataAnonClassNoParentheses + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testAnonClassNoParenthesesNextOpenClose($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + $function = $this->getTargetToken($testMarker, T_FUNCTION); + + $opener = $this->getTargetToken($testMarker, T_OPEN_PARENTHESIS); + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$opener])); + $this->assertSame($function, $tokens[$opener]['parenthesis_owner']); + + $closer = $this->getTargetToken($testMarker, T_CLOSE_PARENTHESIS); + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$closer])); + $this->assertSame($function, $tokens[$closer]['parenthesis_owner']); + + }//end testAnonClassNoParenthesesNextOpenClose() + + + /** + * Data provider. + * + * @see testAnonClassNoParentheses() + * @see testAnonClassNoParenthesesNextOpenClose() + * + * @return array + */ + public function dataAnonClassNoParentheses() + { + return [ + ['/* testNoParentheses */'], + ['/* testNoParenthesesAndEmptyTokens */'], + ]; + + }//end dataAnonClassNoParentheses() + + + /** + * Test that anonymous class tokens with parenthesis get assigned a parenthesis owner, + * opener and closer; and that the opener/closer get the anonymous class assigned as owner. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataAnonClassWithParentheses + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testAnonClassWithParentheses($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + $anonClass = $this->getTargetToken($testMarker, T_ANON_CLASS); + $opener = $this->getTargetToken($testMarker, T_OPEN_PARENTHESIS); + $closer = $this->getTargetToken($testMarker, T_CLOSE_PARENTHESIS); + + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$anonClass])); + $this->assertTrue(array_key_exists('parenthesis_opener', $tokens[$anonClass])); + $this->assertTrue(array_key_exists('parenthesis_closer', $tokens[$anonClass])); + $this->assertSame($anonClass, $tokens[$anonClass]['parenthesis_owner']); + $this->assertSame($opener, $tokens[$anonClass]['parenthesis_opener']); + $this->assertSame($closer, $tokens[$anonClass]['parenthesis_closer']); + + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$opener])); + $this->assertTrue(array_key_exists('parenthesis_opener', $tokens[$opener])); + $this->assertTrue(array_key_exists('parenthesis_closer', $tokens[$opener])); + $this->assertSame($anonClass, $tokens[$opener]['parenthesis_owner']); + $this->assertSame($opener, $tokens[$opener]['parenthesis_opener']); + $this->assertSame($closer, $tokens[$opener]['parenthesis_closer']); + + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$closer])); + $this->assertTrue(array_key_exists('parenthesis_opener', $tokens[$closer])); + $this->assertTrue(array_key_exists('parenthesis_closer', $tokens[$closer])); + $this->assertSame($anonClass, $tokens[$closer]['parenthesis_owner']); + $this->assertSame($opener, $tokens[$closer]['parenthesis_opener']); + $this->assertSame($closer, $tokens[$closer]['parenthesis_closer']); + + }//end testAnonClassWithParentheses() + + + /** + * Data provider. + * + * @see testAnonClassWithParentheses() + * + * @return array + */ + public function dataAnonClassWithParentheses() + { + return [ + ['/* testWithParentheses */'], + ['/* testWithParenthesesAndEmptyTokens */'], + ]; + + }//end dataAnonClassWithParentheses() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.inc new file mode 100644 index 0000000..ce5c553 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.inc @@ -0,0 +1,35 @@ + 10); + +/* testArrayWithComment */ +$var = Array /*comment*/ (1 => 10); + +/* testNestingArray */ +$var = array( + /* testNestedArray */ + array( + 'key' => 'value', + + /* testClosureReturnType */ + 'closure' => function($a) use($global) : Array {}, + ), +); + +/* testFunctionDeclarationParamType */ +function foo(array $a) {} + +/* testFunctionDeclarationReturnType */ +function foo($a) : int|array|null {} + +class Bar { + /* testClassConst */ + const ARRAY = []; + + /* testClassMethod */ + public function array() {} +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.php new file mode 100644 index 0000000..b831ed7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ArrayKeywordTest.php @@ -0,0 +1,170 @@ + + * @copyright 2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class ArrayKeywordTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the array keyword is correctly tokenized as `T_ARRAY`. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent Optional. The token content to look for. + * + * @dataProvider dataArrayKeyword + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createTokenMap + * + * @return void + */ + public function testArrayKeyword($testMarker, $testContent='array') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_ARRAY, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_ARRAY, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_ARRAY (code)'); + $this->assertSame('T_ARRAY', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_ARRAY (type)'); + + $this->assertArrayHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is not set'); + $this->assertArrayHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is not set'); + $this->assertArrayHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is not set'); + + }//end testArrayKeyword() + + + /** + * Data provider. + * + * @see testArrayKeyword() + * + * @return array + */ + public function dataArrayKeyword() + { + return [ + 'empty array' => ['/* testEmptyArray */'], + 'array with space before parenthesis' => ['/* testArrayWithSpace */'], + 'array with comment before parenthesis' => [ + '/* testArrayWithComment */', + 'Array', + ], + 'nested: outer array' => ['/* testNestingArray */'], + 'nested: inner array' => ['/* testNestedArray */'], + ]; + + }//end dataArrayKeyword() + + + /** + * Test that the array keyword when used in a type declaration is correctly tokenized as `T_STRING`. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent Optional. The token content to look for. + * + * @dataProvider dataArrayType + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createTokenMap + * + * @return void + */ + public function testArrayType($testMarker, $testContent='array') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_ARRAY, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_STRING, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (code)'); + $this->assertSame('T_STRING', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (type)'); + + $this->assertArrayNotHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is set'); + $this->assertArrayNotHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is set'); + $this->assertArrayNotHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is set'); + + }//end testArrayType() + + + /** + * Data provider. + * + * @see testArrayType() + * + * @return array + */ + public function dataArrayType() + { + return [ + 'closure return type' => [ + '/* testClosureReturnType */', + 'Array', + ], + 'function param type' => ['/* testFunctionDeclarationParamType */'], + 'function union return type' => ['/* testFunctionDeclarationReturnType */'], + ]; + + }//end dataArrayType() + + + /** + * Verify that the retokenization of `T_ARRAY` tokens to `T_STRING` is handled correctly + * for tokens with the contents 'array' which aren't in actual fact the array keyword. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotArrayKeyword + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createTokenMap + * + * @return void + */ + public function testNotArrayKeyword($testMarker, $testContent='array') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_ARRAY, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_STRING, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (code)'); + $this->assertSame('T_STRING', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (type)'); + + $this->assertArrayNotHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is set'); + $this->assertArrayNotHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is set'); + $this->assertArrayNotHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is set'); + + }//end testNotArrayKeyword() + + + /** + * Data provider. + * + * @see testNotArrayKeyword() + * + * @return array + */ + public function dataNotArrayKeyword() + { + return [ + 'class-constant-name' => [ + '/* testClassConst */', + 'ARRAY', + ], + 'class-method-name' => ['/* testClassMethod */'], + ]; + + }//end dataNotArrayKeyword() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.inc new file mode 100644 index 0000000..e539adf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.inc @@ -0,0 +1,90 @@ + 'foobar'])] +function attribute_with_params_on_function_test() {} + +/* testAttributeWithShortClosureParameter */ +#[AttributeWithParams(static fn ($value) => ! $value)] +function attribute_with_short_closure_param_test() {} + +/* testTwoAttributeOnTheSameLine */ +#[CustomAttribute] #[AttributeWithParams('foo')] +function two_attribute_on_same_line_test() {} + +/* testAttributeAndCommentOnTheSameLine */ +#[CustomAttribute] // This is a comment +function attribute_and_line_comment_on_same_line_test() {} + +/* testAttributeGrouping */ +#[CustomAttribute, AttributeWithParams('foo'), AttributeWithParams('foo', bar: ['bar' => 'foobar'])] +function attribute_grouping_test() {} + +/* testAttributeMultiline */ +#[ + CustomAttribute, + AttributeWithParams('foo'), + AttributeWithParams('foo', bar: ['bar' => 'foobar']) +] +function attribute_multiline_test() {} + +/* testAttributeMultilineWithComment */ +#[ + CustomAttribute, // comment + AttributeWithParams(/* another comment */ 'foo'), + AttributeWithParams('foo', bar: ['bar' => 'foobar']) +] +function attribute_multiline_with_comment_test() {} + +/* testSingleAttributeOnParameter */ +function single_attribute_on_parameter_test(#[ParamAttribute] int $param) {} + +/* testMultipleAttributesOnParameter */ +function multiple_attributes_on_parameter_test(#[ParamAttribute, AttributeWithParams(/* another comment */ 'foo')] int $param) {} + +/* testFqcnAttribute */ +#[Boo\QualifiedName, \Foo\FullyQualifiedName('foo')] +function fqcn_attrebute_test() {} + +/* testNestedAttributes */ +#[Boo\QualifiedName(fn (#[AttributeOne('boo')] $value) => (string) $value)] +function nested_attributes_test() {} + +/* testMultilineAttributesOnParameter */ +function multiline_attributes_on_parameter_test(#[ + AttributeWithParams( + 'foo' + ) + ] int $param) {} + +/* testAttributeContainingTextLookingLikeCloseTag */ +#[DeprecationReason('reason: ')] +function attribute_containing_text_looking_like_close_tag() {} + +/* testAttributeContainingMultilineTextLookingLikeCloseTag */ +#[DeprecationReason( + 'reason: ' +)] +function attribute_containing_mulitline_text_looking_like_close_tag() {} + +/* testInvalidAttribute */ +#[ThisIsNotAnAttribute +function invalid_attribute_test() {} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.php new file mode 100644 index 0000000..1593f0f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/AttributesTest.php @@ -0,0 +1,658 @@ + + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class AttributesTest extends AbstractMethodUnitTest +{ + + + /** + * Test that attributes are parsed correctly. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int $length The number of tokens between opener and closer. + * @param array $tokenCodes The codes of tokens inside the attributes. + * + * @dataProvider dataAttribute + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testAttribute($testMarker, $length, $tokenCodes) + { + $tokens = self::$phpcsFile->getTokens(); + + $attribute = $this->getTargetToken($testMarker, T_ATTRIBUTE); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(($attribute + $length), $closer); + + $this->assertSame(T_ATTRIBUTE_END, $tokens[$closer]['code']); + + $this->assertSame($tokens[$attribute]['attribute_opener'], $tokens[$closer]['attribute_opener']); + $this->assertSame($tokens[$attribute]['attribute_closer'], $tokens[$closer]['attribute_closer']); + + $map = array_map( + function ($token) use ($attribute, $length) { + $this->assertArrayHasKey('attribute_closer', $token); + $this->assertSame(($attribute + $length), $token['attribute_closer']); + + return $token['code']; + }, + array_slice($tokens, ($attribute + 1), ($length - 1)) + ); + + $this->assertSame($tokenCodes, $map); + + }//end testAttribute() + + + /** + * Data provider. + * + * @see testAttribute() + * + * @return array + */ + public function dataAttribute() + { + return [ + [ + '/* testAttribute */', + 2, + [ T_STRING ], + ], + [ + '/* testAttributeWithParams */', + 7, + [ + T_STRING, + T_OPEN_PARENTHESIS, + T_STRING, + T_DOUBLE_COLON, + T_STRING, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testAttributeWithNamedParam */', + 10, + [ + T_STRING, + T_OPEN_PARENTHESIS, + T_PARAM_NAME, + T_COLON, + T_WHITESPACE, + T_STRING, + T_DOUBLE_COLON, + T_STRING, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testAttributeOnFunction */', + 2, + [ T_STRING ], + ], + [ + '/* testAttributeOnFunctionWithParams */', + 17, + [ + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_COMMA, + T_WHITESPACE, + T_PARAM_NAME, + T_COLON, + T_WHITESPACE, + T_OPEN_SHORT_ARRAY, + T_CONSTANT_ENCAPSED_STRING, + T_WHITESPACE, + T_DOUBLE_ARROW, + T_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_SHORT_ARRAY, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testAttributeWithShortClosureParameter */', + 17, + [ + T_STRING, + T_OPEN_PARENTHESIS, + T_STATIC, + T_WHITESPACE, + T_FN, + T_WHITESPACE, + T_OPEN_PARENTHESIS, + T_VARIABLE, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + T_FN_ARROW, + T_WHITESPACE, + T_BOOLEAN_NOT, + T_WHITESPACE, + T_VARIABLE, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testAttributeGrouping */', + 26, + [ + T_STRING, + T_COMMA, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_PARENTHESIS, + T_COMMA, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_COMMA, + T_WHITESPACE, + T_PARAM_NAME, + T_COLON, + T_WHITESPACE, + T_OPEN_SHORT_ARRAY, + T_CONSTANT_ENCAPSED_STRING, + T_WHITESPACE, + T_DOUBLE_ARROW, + T_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_SHORT_ARRAY, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testAttributeMultiline */', + 31, + [ + T_WHITESPACE, + T_WHITESPACE, + T_STRING, + T_COMMA, + T_WHITESPACE, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_PARENTHESIS, + T_COMMA, + T_WHITESPACE, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_COMMA, + T_WHITESPACE, + T_PARAM_NAME, + T_COLON, + T_WHITESPACE, + T_OPEN_SHORT_ARRAY, + T_CONSTANT_ENCAPSED_STRING, + T_WHITESPACE, + T_DOUBLE_ARROW, + T_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_SHORT_ARRAY, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + ], + ], + [ + '/* testFqcnAttribute */', + 13, + [ + T_STRING, + T_NS_SEPARATOR, + T_STRING, + T_COMMA, + T_WHITESPACE, + T_NS_SEPARATOR, + T_STRING, + T_NS_SEPARATOR, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_PARENTHESIS, + ], + ], + ]; + + }//end dataAttribute() + + + /** + * Test that multiple attributes on the same line are parsed correctly. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testTwoAttributesOnTheSameLine() + { + $tokens = self::$phpcsFile->getTokens(); + + $attribute = $this->getTargetToken('/* testTwoAttributeOnTheSameLine */', T_ATTRIBUTE); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(T_WHITESPACE, $tokens[($closer + 1)]['code']); + $this->assertSame(T_ATTRIBUTE, $tokens[($closer + 2)]['code']); + $this->assertArrayHasKey('attribute_closer', $tokens[($closer + 2)]); + + }//end testTwoAttributesOnTheSameLine() + + + /** + * Test that attribute followed by a line comment is parsed correctly. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testAttributeAndLineComment() + { + $tokens = self::$phpcsFile->getTokens(); + + $attribute = $this->getTargetToken('/* testAttributeAndCommentOnTheSameLine */', T_ATTRIBUTE); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(T_WHITESPACE, $tokens[($closer + 1)]['code']); + $this->assertSame(T_COMMENT, $tokens[($closer + 2)]['code']); + + }//end testAttributeAndLineComment() + + + /** + * Test that attributes on function declaration parameters are parsed correctly. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int $position The token position (starting from T_FUNCTION) of T_ATTRIBUTE token. + * @param int $length The number of tokens between opener and closer. + * @param array $tokenCodes The codes of tokens inside the attributes. + * + * @dataProvider dataAttributeOnParameters + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testAttributeOnParameters($testMarker, $position, $length, array $tokenCodes) + { + $tokens = self::$phpcsFile->getTokens(); + + $function = $this->getTargetToken($testMarker, T_FUNCTION); + $attribute = ($function + $position); + + $this->assertSame(T_ATTRIBUTE, $tokens[$attribute]['code']); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $this->assertSame(($attribute + $length), $tokens[$attribute]['attribute_closer']); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(T_WHITESPACE, $tokens[($closer + 1)]['code']); + $this->assertSame(T_STRING, $tokens[($closer + 2)]['code']); + $this->assertSame('int', $tokens[($closer + 2)]['content']); + + $this->assertSame(T_VARIABLE, $tokens[($closer + 4)]['code']); + $this->assertSame('$param', $tokens[($closer + 4)]['content']); + + $map = array_map( + function ($token) use ($attribute, $length) { + $this->assertArrayHasKey('attribute_closer', $token); + $this->assertSame(($attribute + $length), $token['attribute_closer']); + + return $token['code']; + }, + array_slice($tokens, ($attribute + 1), ($length - 1)) + ); + + $this->assertSame($tokenCodes, $map); + + }//end testAttributeOnParameters() + + + /** + * Data provider. + * + * @see testAttributeOnParameters() + * + * @return array + */ + public function dataAttributeOnParameters() + { + return [ + [ + '/* testSingleAttributeOnParameter */', + 4, + 2, + [T_STRING], + ], + [ + '/* testMultipleAttributesOnParameter */', + 4, + 10, + [ + T_STRING, + T_COMMA, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_COMMENT, + T_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_PARENTHESIS, + ], + ], + [ + '/* testMultilineAttributesOnParameter */', + 4, + 13, + [ + T_WHITESPACE, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_WHITESPACE, + T_WHITESPACE, + T_CONSTANT_ENCAPSED_STRING, + T_WHITESPACE, + T_WHITESPACE, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + T_WHITESPACE, + ], + ], + ]; + + }//end dataAttributeOnParameters() + + + /** + * Test that an attribute containing text which looks like a PHP close tag is tokenized correctly. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param int $length The number of tokens between opener and closer. + * @param array $expectedTokensAttribute The codes of tokens inside the attributes. + * @param array $expectedTokensAfter The codes of tokens after the attributes. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @dataProvider dataAttributeOnTextLookingLikeCloseTag + * + * @return void + */ + public function testAttributeContainingTextLookingLikeCloseTag($testMarker, $length, array $expectedTokensAttribute, array $expectedTokensAfter) + { + $tokens = self::$phpcsFile->getTokens(); + + $attribute = $this->getTargetToken($testMarker, T_ATTRIBUTE); + + $this->assertSame('T_ATTRIBUTE', $tokens[$attribute]['type']); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(($attribute + $length), $closer); + $this->assertSame(T_ATTRIBUTE_END, $tokens[$closer]['code']); + $this->assertSame('T_ATTRIBUTE_END', $tokens[$closer]['type']); + + $this->assertSame($tokens[$attribute]['attribute_opener'], $tokens[$closer]['attribute_opener']); + $this->assertSame($tokens[$attribute]['attribute_closer'], $tokens[$closer]['attribute_closer']); + + $i = ($attribute + 1); + foreach ($expectedTokensAttribute as $item) { + list($expectedType, $expectedContents) = $item; + $this->assertSame($expectedType, $tokens[$i]['type']); + $this->assertSame($expectedContents, $tokens[$i]['content']); + $this->assertArrayHasKey('attribute_opener', $tokens[$i]); + $this->assertArrayHasKey('attribute_closer', $tokens[$i]); + ++$i; + } + + $i = ($closer + 1); + foreach ($expectedTokensAfter as $expectedCode) { + $this->assertSame($expectedCode, $tokens[$i]['code']); + ++$i; + } + + }//end testAttributeContainingTextLookingLikeCloseTag() + + + /** + * Data provider. + * + * @see dataAttributeOnTextLookingLikeCloseTag() + * + * @return array + */ + public function dataAttributeOnTextLookingLikeCloseTag() + { + return [ + [ + '/* testAttributeContainingTextLookingLikeCloseTag */', + 5, + [ + [ + 'T_STRING', + 'DeprecationReason', + ], + [ + 'T_OPEN_PARENTHESIS', + '(', + ], + [ + 'T_CONSTANT_ENCAPSED_STRING', + "'reason: '", + ], + [ + 'T_CLOSE_PARENTHESIS', + ')', + ], + [ + 'T_ATTRIBUTE_END', + ']', + ], + ], + [ + T_WHITESPACE, + T_FUNCTION, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + T_OPEN_CURLY_BRACKET, + T_CLOSE_CURLY_BRACKET, + ], + ], + [ + '/* testAttributeContainingMultilineTextLookingLikeCloseTag */', + 8, + [ + [ + 'T_STRING', + 'DeprecationReason', + ], + [ + 'T_OPEN_PARENTHESIS', + '(', + ], + [ + 'T_WHITESPACE', + "\n", + ], + [ + 'T_WHITESPACE', + " ", + ], + [ + 'T_CONSTANT_ENCAPSED_STRING', + "'reason: '", + ], + [ + 'T_WHITESPACE', + "\n", + ], + [ + 'T_CLOSE_PARENTHESIS', + ')', + ], + [ + 'T_ATTRIBUTE_END', + ']', + ], + ], + [ + T_WHITESPACE, + T_FUNCTION, + T_WHITESPACE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + T_OPEN_CURLY_BRACKET, + T_CLOSE_CURLY_BRACKET, + ], + ], + ]; + + }//end dataAttributeOnTextLookingLikeCloseTag() + + + /** + * Test that invalid attribute (or comment starting with #[ and without ]) are parsed correctly. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testInvalidAttribute() + { + $tokens = self::$phpcsFile->getTokens(); + + $attribute = $this->getTargetToken('/* testInvalidAttribute */', T_ATTRIBUTE); + + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + $this->assertNull($tokens[$attribute]['attribute_closer']); + + }//end testInvalidAttribute() + + + /** + * Test that nested attributes are parsed correctly. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::findCloser + * @covers PHP_CodeSniffer\Tokenizers\PHP::parsePhpAttribute + * + * @return void + */ + public function testNestedAttributes() + { + $tokens = self::$phpcsFile->getTokens(); + $tokenCodes = [ + T_STRING, + T_NS_SEPARATOR, + T_STRING, + T_OPEN_PARENTHESIS, + T_FN, + T_WHITESPACE, + T_OPEN_PARENTHESIS, + T_ATTRIBUTE, + T_STRING, + T_OPEN_PARENTHESIS, + T_CONSTANT_ENCAPSED_STRING, + T_CLOSE_PARENTHESIS, + T_ATTRIBUTE_END, + T_WHITESPACE, + T_VARIABLE, + T_CLOSE_PARENTHESIS, + T_WHITESPACE, + T_FN_ARROW, + T_WHITESPACE, + T_STRING_CAST, + T_WHITESPACE, + T_VARIABLE, + T_CLOSE_PARENTHESIS, + ]; + + $attribute = $this->getTargetToken('/* testNestedAttributes */', T_ATTRIBUTE); + $this->assertArrayHasKey('attribute_closer', $tokens[$attribute]); + + $closer = $tokens[$attribute]['attribute_closer']; + $this->assertSame(($attribute + 24), $closer); + + $this->assertSame(T_ATTRIBUTE_END, $tokens[$closer]['code']); + + $this->assertSame($tokens[$attribute]['attribute_opener'], $tokens[$closer]['attribute_opener']); + $this->assertSame($tokens[$attribute]['attribute_closer'], $tokens[$closer]['attribute_closer']); + + $this->assertArrayNotHasKey('nested_attributes', $tokens[$attribute]); + $this->assertArrayHasKey('nested_attributes', $tokens[($attribute + 8)]); + $this->assertSame([$attribute => ($attribute + 24)], $tokens[($attribute + 8)]['nested_attributes']); + + $test = function (array $tokens, $length, $nestedMap) use ($attribute) { + foreach ($tokens as $token) { + $this->assertArrayHasKey('attribute_closer', $token); + $this->assertSame(($attribute + $length), $token['attribute_closer']); + $this->assertSame($nestedMap, $token['nested_attributes']); + } + }; + + $test(array_slice($tokens, ($attribute + 1), 7), 24, [$attribute => $attribute + 24]); + $test(array_slice($tokens, ($attribute + 8), 1), 8 + 5, [$attribute => $attribute + 24]); + + // Length here is 8 (nested attribute offset) + 5 (real length). + $test( + array_slice($tokens, ($attribute + 9), 4), + 8 + 5, + [ + $attribute => $attribute + 24, + $attribute + 8 => $attribute + 13, + ] + ); + + $test(array_slice($tokens, ($attribute + 13), 1), 8 + 5, [$attribute => $attribute + 24]); + $test(array_slice($tokens, ($attribute + 14), 10), 24, [$attribute => $attribute + 24]); + + $map = array_map( + static function ($token) { + return $token['code']; + }, + array_slice($tokens, ($attribute + 1), 23) + ); + + $this->assertSame($tokenCodes, $map); + + }//end testNestedAttributes() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.inc new file mode 100644 index 0000000..82bfe24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.inc @@ -0,0 +1,95 @@ +enum = 'foo'; + } +} + +/* testEnumUsedAsFunctionName */ +function enum() +{ +} + +/* testDeclarationContainingComment */ +enum /* comment */ Name +{ + case SOME_CASE; +} + +enum /* testEnumUsedAsEnumName */ Enum +{ +} + +/* testEnumUsedAsNamespaceName */ +namespace Enum; +/* testEnumUsedAsPartOfNamespaceName */ +namespace My\Enum\Collection; +/* testEnumUsedInObjectInitialization */ +$obj = new Enum; +/* testEnumAsFunctionCall */ +$var = enum($a, $b); +/* testEnumAsFunctionCallWithNamespace */ +var = namespace\enum(); +/* testClassConstantFetchWithEnumAsClassName */ +echo Enum::CONSTANT; +/* testClassConstantFetchWithEnumAsConstantName */ +echo ClassName::ENUM; + +/* testParseErrorMissingName */ +enum { + case SOME_CASE; +} + +/* testParseErrorLiveCoding */ +// This must be the last test in the file. +enum diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.php new file mode 100644 index 0000000..7c72672 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillEnumTest.php @@ -0,0 +1,229 @@ + + * @copyright 2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BackfillEnumTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the "enum" keyword is tokenized as such. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $testContent The token content to look for. + * @param int $openerOffset Offset to find expected scope opener. + * @param int $closerOffset Offset to find expected scope closer. + * + * @dataProvider dataEnums + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testEnums($testMarker, $testContent, $openerOffset, $closerOffset) + { + $tokens = self::$phpcsFile->getTokens(); + + $enum = $this->getTargetToken($testMarker, [T_ENUM, T_STRING], $testContent); + + $this->assertSame(T_ENUM, $tokens[$enum]['code']); + $this->assertSame('T_ENUM', $tokens[$enum]['type']); + + $this->assertArrayHasKey('scope_condition', $tokens[$enum]); + $this->assertArrayHasKey('scope_opener', $tokens[$enum]); + $this->assertArrayHasKey('scope_closer', $tokens[$enum]); + + $this->assertSame($enum, $tokens[$enum]['scope_condition']); + + $scopeOpener = $tokens[$enum]['scope_opener']; + $scopeCloser = $tokens[$enum]['scope_closer']; + + $expectedScopeOpener = ($enum + $openerOffset); + $expectedScopeCloser = ($enum + $closerOffset); + + $this->assertSame($expectedScopeOpener, $scopeOpener); + $this->assertArrayHasKey('scope_condition', $tokens[$scopeOpener]); + $this->assertArrayHasKey('scope_opener', $tokens[$scopeOpener]); + $this->assertArrayHasKey('scope_closer', $tokens[$scopeOpener]); + $this->assertSame($enum, $tokens[$scopeOpener]['scope_condition']); + $this->assertSame($scopeOpener, $tokens[$scopeOpener]['scope_opener']); + $this->assertSame($scopeCloser, $tokens[$scopeOpener]['scope_closer']); + + $this->assertSame($expectedScopeCloser, $scopeCloser); + $this->assertArrayHasKey('scope_condition', $tokens[$scopeCloser]); + $this->assertArrayHasKey('scope_opener', $tokens[$scopeCloser]); + $this->assertArrayHasKey('scope_closer', $tokens[$scopeCloser]); + $this->assertSame($enum, $tokens[$scopeCloser]['scope_condition']); + $this->assertSame($scopeOpener, $tokens[$scopeCloser]['scope_opener']); + $this->assertSame($scopeCloser, $tokens[$scopeCloser]['scope_closer']); + + }//end testEnums() + + + /** + * Data provider. + * + * @see testEnums() + * + * @return array + */ + public function dataEnums() + { + return [ + [ + '/* testPureEnum */', + 'enum', + 4, + 12, + ], + [ + '/* testBackedIntEnum */', + 'enum', + 7, + 29, + ], + [ + '/* testBackedStringEnum */', + 'enum', + 8, + 30, + ], + [ + '/* testComplexEnum */', + 'enum', + 11, + 72, + ], + [ + '/* testEnumWithEnumAsClassName */', + 'enum', + 6, + 7, + ], + [ + '/* testEnumIsCaseInsensitive */', + 'EnUm', + 4, + 5, + ], + [ + '/* testDeclarationContainingComment */', + 'enum', + 6, + 14, + ], + ]; + + }//end dataEnums() + + + /** + * Test that "enum" when not used as the keyword is still tokenized as `T_STRING`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotEnums + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNotEnums($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, [T_ENUM, T_STRING], $testContent); + $this->assertSame(T_STRING, $tokens[$target]['code']); + $this->assertSame('T_STRING', $tokens[$target]['type']); + + }//end testNotEnums() + + + /** + * Data provider. + * + * @see testNotEnums() + * + * @return array + */ + public function dataNotEnums() + { + return [ + [ + '/* testEnumAsClassNameAfterEnumKeyword */', + 'Enum', + ], + [ + '/* testEnumUsedAsClassName */', + 'Enum', + ], + [ + '/* testEnumUsedAsClassConstantName */', + 'ENUM', + ], + [ + '/* testEnumUsedAsMethodName */', + 'enum', + ], + [ + '/* testEnumUsedAsPropertyName */', + 'enum', + ], + [ + '/* testEnumUsedAsFunctionName */', + 'enum', + ], + [ + '/* testEnumUsedAsEnumName */', + 'Enum', + ], + [ + '/* testEnumUsedAsNamespaceName */', + 'Enum', + ], + [ + '/* testEnumUsedAsPartOfNamespaceName */', + 'Enum', + ], + [ + '/* testEnumUsedInObjectInitialization */', + 'Enum', + ], + [ + '/* testEnumAsFunctionCall */', + 'enum', + ], + [ + '/* testEnumAsFunctionCallWithNamespace */', + 'enum', + ], + [ + '/* testClassConstantFetchWithEnumAsClassName */', + 'Enum', + ], + [ + '/* testClassConstantFetchWithEnumAsConstantName */', + 'ENUM', + ], + [ + '/* testParseErrorMissingName */', + 'enum', + ], + [ + '/* testParseErrorLiveCoding */', + 'enum', + ], + ]; + + }//end dataNotEnums() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillExplicitOctalNotationTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillExplicitOctalNotationTest.inc new file mode 100644 index 0000000..eb907ed --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillExplicitOctalNotationTest.inc @@ -0,0 +1,31 @@ + + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BackfillExplicitOctalNotationTest extends AbstractMethodUnitTest +{ + + + /** + * Test that explicitly-defined octal values are tokenized as a single number and not as a number and a string. + * + * @param string $marker The comment which prefaces the target token in the test file. + * @param string $value The expected content of the token + * @param int|string $nextToken The expected next token. + * @param string $nextContent The expected content of the next token. + * + * @dataProvider dataExplicitOctalNotation + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testExplicitOctalNotation($marker, $value, $nextToken, $nextContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $number = $this->getTargetToken($marker, [T_LNUMBER]); + + $this->assertSame($value, $tokens[$number]['content'], 'Content of integer token does not match expectation'); + + $this->assertSame($nextToken, $tokens[($number + 1)]['code'], 'Next token is not the expected type, but '.$tokens[($number + 1)]['type']); + $this->assertSame($nextContent, $tokens[($number + 1)]['content'], 'Next token did not have the expected contents'); + + }//end testExplicitOctalNotation() + + + /** + * Data provider. + * + * @see testExplicitOctalNotation() + * + * @return array + */ + public function dataExplicitOctalNotation() + { + return [ + [ + 'marker' => '/* testExplicitOctal */', + 'value' => '0o137041', + 'nextToken' => T_SEMICOLON, + 'nextContent' => ';', + ], + [ + 'marker' => '/* testExplicitOctalCapitalised */', + 'value' => '0O137041', + 'nextToken' => T_SEMICOLON, + 'nextContent' => ';', + ], + [ + 'marker' => '/* testExplicitOctalWithNumericSeparator */', + 'value' => '0o137_041', + 'nextToken' => T_SEMICOLON, + 'nextContent' => ';', + ], + [ + 'marker' => '/* testInvalid1 */', + 'value' => '0', + 'nextToken' => T_STRING, + 'nextContent' => 'o_137', + ], + [ + 'marker' => '/* testInvalid2 */', + 'value' => '0', + 'nextToken' => T_STRING, + 'nextContent' => 'O_41', + ], + [ + 'marker' => '/* testInvalid3 */', + 'value' => '0', + 'nextToken' => T_STRING, + 'nextContent' => 'o91', + ], + [ + 'marker' => '/* testInvalid4 */', + 'value' => '0O2', + 'nextToken' => T_LNUMBER, + 'nextContent' => '82', + ], + [ + 'marker' => '/* testInvalid5 */', + 'value' => '0o2', + 'nextToken' => T_LNUMBER, + 'nextContent' => '8_2', + ], + [ + 'marker' => '/* testInvalid6 */', + 'value' => '0o2', + 'nextToken' => T_STRING, + 'nextContent' => '_82', + ], + [ + 'marker' => '/* testInvalid7 */', + 'value' => '0', + 'nextToken' => T_STRING, + 'nextContent' => 'o', + ], + ]; + + }//end dataExplicitOctalNotation() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.inc new file mode 100644 index 0000000..13f165b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.inc @@ -0,0 +1,198 @@ + $x + $y; + +/* testMixedCase */ +$fn1 = Fn($x) => $x + $y; + +/* testWhitespace */ +$fn1 = fn ($x) => $x + $y; + +/* testComment */ +$fn1 = fn /* comment here */ ($x) => $x + $y; + +/* testHeredoc */ +$fn1 = fn() => << /* testNestedInner */ fn($y) => $x * $y + $z; + +/* testNestedSharedCloserOuter */ +$foo = foo(fn() => /* testNestedSharedCloserInner */ fn() => bar() === true); + +/* testFunctionCall */ +$extended = fn($c) => $callable($factory($c), $c); + +/* testChainedFunctionCall */ +$result = Collection::from([1, 2]) + ->map(fn($v) => $v * 2) + ->reduce(/* testFunctionArgument */ fn($tmp, $v) => $tmp + $v, 0); + +/* testClosure */ +$extended = fn($c) => $callable(function() { + for ($x = 1; $x < 10; $x++) { + echo $x; + } + + echo 'done'; +}, $c); + +/* testArrayIndex */ +$found = in_array_cb($needle, $haystack, fn($array, $needle) => $array[2] === $needle); + +$result = array_map( + /* testReturnType */ + static fn(int $number) : int => $number + 1, + $numbers +); + +/* testReference */ +fn&($x) => $x; + +/* testGrouped */ +(fn($x) => $x) + $y; + +/* testArrayValue */ +$a = [ + 'a' => fn() => return 1, +]; + +/* testArrayValueNoTrailingComma */ +$a = [ + 'a' => fn() => foo() +]; + +/* testYield */ +$a = fn($x) => yield 'k' => $x; + +/* testNullableNamespace */ +$a = fn(?\DateTime $x) : ?\DateTime => $x; + +/* testNamespaceOperatorInTypes */ +$fn = fn(namespace\Foo $a) : ?namespace\Foo => $a; + +/* testSelfReturnType */ +fn(self $a) : self => $a; + +/* testParentReturnType */ +fn(parent $a) : parent => $a; + +/* testCallableReturnType */ +fn(callable $a) : callable => $a; + +/* testArrayReturnType */ +fn(array $a) : array => $a; + +/* testStaticReturnType */ +fn(array $a) : static => $a; + +/* testUnionParamType */ +$arrowWithUnionParam = fn(int|float $param) : SomeClass => new SomeClass($param); + +/* testUnionReturnType */ +$arrowWithUnionReturn = fn($param) : int|float => $param | 10; + +/* testTernary */ +$fn = fn($a) => $a ? /* testTernaryThen */ fn() : string => 'a' : /* testTernaryElse */ fn() : string => 'b'; + +/* testTernaryWithTypes */ +$fn = fn(int|null $a) : array|null => $a ? null : []; + +function matchInArrow($x) { + /* testWithMatchValue */ + $fn = fn($x) => match(true) { + 1, 2, 3, 4, 5 => 'foo', + default => 'bar', + }; +} + +function matchInArrowAndMore($x) { + /* testWithMatchValueAndMore */ + $fn = fn($x) => match(true) { + 1, 2, 3, 4, 5 => 'foo', + default => 'bar', + } . 'suffix'; +} + +function arrowFunctionInMatchWithTrailingComma($x) { + return match ($x) { + /* testInMatchNotLastValue */ + 1 => fn($y) => callMe($y), + /* testInMatchLastValueWithTrailingComma */ + default => fn($y) => callThem($y), + }; +} + +function arrowFunctionInMatchNoTrailingComma1($x) { + return match ($x) { + 1 => fn($y) => callMe($y), + /* testInMatchLastValueNoTrailingComma1 */ + default => fn($y) => callThem($y) + }; +} + +function arrowFunctionInMatchNoTrailingComma2($x) { + return match ($x) { + /* testInMatchLastValueNoTrailingComma2 */ + default => fn($y) => 5 * $y + }; +} + +/* testConstantDeclaration */ +const FN = 'a'; + +/* testConstantDeclarationLower */ +const fn = 'a'; + +class Foo { + /* testStaticMethodName */ + public static function fn($param) { + /* testNestedInMethod */ + $fn = fn($c) => $callable($factory($c), $c); + } + + public function foo() { + /* testPropertyAssignment */ + $this->fn = 'a'; + } +} + +$anon = new class() { + /* testAnonClassMethodName */ + protected function fN($param) { + } +} + +/* testNonArrowStaticMethodCall */ +$a = Foo::fn($param); + +/* testNonArrowConstantAccess */ +$a = MyClass::FN; + +/* testNonArrowConstantAccessMixed */ +$a = MyClass::Fn; + +/* testNonArrowObjectMethodCall */ +$a = $obj->fn($param); + +/* testNonArrowObjectMethodCallUpper */ +$a = $obj->FN($param); + +/* testNonArrowNamespacedFunctionCall */ +$a = MyNS\Sub\Fn($param); + +/* testNonArrowNamespaceOperatorFunctionCall */ +$a = namespace\fn($param); + +/* testNonArrowFunctionNameWithUnionTypes */ +function fn(int|float $param) : string|null {} + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +$fn = fn diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.php new file mode 100644 index 0000000..e693533 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillFnTokenTest.php @@ -0,0 +1,802 @@ + + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BackfillFnTokenTest extends AbstractMethodUnitTest +{ + + + /** + * Test simple arrow functions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testSimple() + { + foreach (['/* testStandard */', '/* testMixedCase */'] as $comment) { + $token = $this->getTargetToken($comment, T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 12); + } + + }//end testSimple() + + + /** + * Test whitespace inside arrow function definitions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testWhitespace() + { + $token = $this->getTargetToken('/* testWhitespace */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 6, 13); + + }//end testWhitespace() + + + /** + * Test comments inside arrow function definitions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testComment() + { + $token = $this->getTargetToken('/* testComment */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 8, 15); + + }//end testComment() + + + /** + * Test heredocs inside arrow function definitions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testHeredoc() + { + $token = $this->getTargetToken('/* testHeredoc */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 4, 9); + + }//end testHeredoc() + + + /** + * Test nested arrow functions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNestedOuter() + { + $token = $this->getTargetToken('/* testNestedOuter */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 25); + + }//end testNestedOuter() + + + /** + * Test nested arrow functions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNestedInner() + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken('/* testNestedInner */', T_FN); + $this->backfillHelper($token, true); + + $expectedScopeOpener = ($token + 5); + $expectedScopeCloser = ($token + 16); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], 'Scope opener is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], 'Scope closer is not the semicolon token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'Opener scope opener is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'Opener scope closer is not the semicolon token'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame(($token - 4), $tokens[$closer]['scope_opener'], 'Closer scope opener is not the arrow token of the "outer" arrow function (shared scope closer)'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'Closer scope closer is not the semicolon token'); + + }//end testNestedInner() + + + /** + * Test nested arrow functions with a shared closer. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNestedSharedCloser() + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken('/* testNestedSharedCloserOuter */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 4, 20); + + $token = $this->getTargetToken('/* testNestedSharedCloserInner */', T_FN); + $this->backfillHelper($token, true); + + $expectedScopeOpener = ($token + 4); + $expectedScopeCloser = ($token + 12); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], 'Scope opener for "inner" arrow function is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], 'Scope closer for "inner" arrow function is not the TRUE token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'Opener scope opener for "inner" arrow function is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'Opener scope closer for "inner" arrow function is not the semicolon token'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame(($token - 4), $tokens[$closer]['scope_opener'], 'Closer scope opener for "inner" arrow function is not the arrow token of the "outer" arrow function (shared scope closer)'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'Closer scope closer for "inner" arrow function is not the TRUE token'); + + }//end testNestedSharedCloser() + + + /** + * Test arrow functions that call functions. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testFunctionCall() + { + $token = $this->getTargetToken('/* testFunctionCall */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 17); + + }//end testFunctionCall() + + + /** + * Test arrow functions that are included in chained calls. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testChainedFunctionCall() + { + $token = $this->getTargetToken('/* testChainedFunctionCall */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 12, 'bracket'); + + }//end testChainedFunctionCall() + + + /** + * Test arrow functions that are used as function arguments. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testFunctionArgument() + { + $token = $this->getTargetToken('/* testFunctionArgument */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 8, 15, 'comma'); + + }//end testFunctionArgument() + + + /** + * Test arrow functions that use closures. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testClosure() + { + $token = $this->getTargetToken('/* testClosure */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 60, 'comma'); + + }//end testClosure() + + + /** + * Test arrow functions using an array index. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testArrayIndex() + { + $token = $this->getTargetToken('/* testArrayIndex */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 8, 17, 'comma'); + + }//end testArrayIndex() + + + /** + * Test arrow functions with a return type. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testReturnType() + { + $token = $this->getTargetToken('/* testReturnType */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 11, 18, 'comma'); + + }//end testReturnType() + + + /** + * Test arrow functions that return a reference. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testReference() + { + $token = $this->getTargetToken('/* testReference */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 6, 9); + + }//end testReference() + + + /** + * Test arrow functions that are grouped by parenthesis. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testGrouped() + { + $token = $this->getTargetToken('/* testGrouped */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 8); + + }//end testGrouped() + + + /** + * Test arrow functions that are used as array values. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testArrayValue() + { + $token = $this->getTargetToken('/* testArrayValue */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 4, 9, 'comma'); + + }//end testArrayValue() + + + /** + * Test arrow functions that are used as array values with no trailing comma. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testArrayValueNoTrailingComma() + { + $token = $this->getTargetToken('/* testArrayValueNoTrailingComma */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 4, 8, 'closing parenthesis'); + + }//end testArrayValueNoTrailingComma() + + + /** + * Test arrow functions that use the yield keyword. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testYield() + { + $token = $this->getTargetToken('/* testYield */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 14); + + }//end testYield() + + + /** + * Test arrow functions that use nullable namespace types. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNullableNamespace() + { + $token = $this->getTargetToken('/* testNullableNamespace */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 15, 18); + + }//end testNullableNamespace() + + + /** + * Test arrow functions that use the namespace operator in the return type. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNamespaceOperatorInTypes() + { + $token = $this->getTargetToken('/* testNamespaceOperatorInTypes */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 16, 19); + + }//end testNamespaceOperatorInTypes() + + + /** + * Test arrow functions that use self/parent/callable/array/static return types. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testKeywordReturnTypes() + { + $tokens = self::$phpcsFile->getTokens(); + + $testMarkers = [ + 'Self', + 'Parent', + 'Callable', + 'Array', + 'Static', + ]; + + foreach ($testMarkers as $marker) { + $token = $this->getTargetToken('/* test'.$marker.'ReturnType */', T_FN); + $this->backfillHelper($token); + + $expectedScopeOpener = ($token + 11); + $expectedScopeCloser = ($token + 14); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], "Scope opener is not the arrow token (for $marker)"); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], "Scope closer is not the semicolon token(for $marker)"); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], "Opener scope opener is not the arrow token(for $marker)"); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], "Opener scope closer is not the semicolon token(for $marker)"); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame($expectedScopeOpener, $tokens[$closer]['scope_opener'], "Closer scope opener is not the arrow token(for $marker)"); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], "Closer scope closer is not the semicolon token(for $marker)"); + } + + }//end testKeywordReturnTypes() + + + /** + * Test arrow function with a union parameter type. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testUnionParamType() + { + $token = $this->getTargetToken('/* testUnionParamType */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 13, 21); + + }//end testUnionParamType() + + + /** + * Test arrow function with a union return type. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testUnionReturnType() + { + $token = $this->getTargetToken('/* testUnionReturnType */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 11, 18); + + }//end testUnionReturnType() + + + /** + * Test arrow functions used in ternary operators. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testTernary() + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken('/* testTernary */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 40); + + $token = $this->getTargetToken('/* testTernaryThen */', T_FN); + $this->backfillHelper($token); + + $expectedScopeOpener = ($token + 8); + $expectedScopeCloser = ($token + 12); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], 'Scope opener for THEN is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], 'Scope closer for THEN is not the semicolon token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'Opener scope opener for THEN is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'Opener scope closer for THEN is not the semicolon token'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame($expectedScopeOpener, $tokens[$closer]['scope_opener'], 'Closer scope opener for THEN is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'Closer scope closer for THEN is not the semicolon token'); + + $token = $this->getTargetToken('/* testTernaryElse */', T_FN); + $this->backfillHelper($token, true); + + $expectedScopeOpener = ($token + 8); + $expectedScopeCloser = ($token + 11); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], 'Scope opener for ELSE is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], 'Scope closer for ELSE is not the semicolon token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'Opener scope opener for ELSE is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'Opener scope closer for ELSE is not the semicolon token'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame(($token - 24), $tokens[$closer]['scope_opener'], 'Closer scope opener for ELSE is not the arrow token of the "outer" arrow function (shared scope closer)'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'Closer scope closer for ELSE is not the semicolon token'); + + }//end testTernary() + + + /** + * Test typed arrow functions used in ternary operators. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testTernaryWithTypes() + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken('/* testTernaryWithTypes */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 15, 27); + + }//end testTernaryWithTypes() + + + /** + * Test arrow function returning a match control structure. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testWithMatchValue() + { + $token = $this->getTargetToken('/* testWithMatchValue */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 44); + + }//end testWithMatchValue() + + + /** + * Test arrow function returning a match control structure with something behind it. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testWithMatchValueAndMore() + { + $token = $this->getTargetToken('/* testWithMatchValueAndMore */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 48); + + }//end testWithMatchValueAndMore() + + + /** + * Test match control structure returning arrow functions. + * + * @param string $testMarker The comment prefacing the target token. + * @param int $openerOffset The expected offset of the scope opener in relation to the testMarker. + * @param int $closerOffset The expected offset of the scope closer in relation to the testMarker. + * @param string $expectedCloserType The type of token expected for the scope closer. + * @param string $expectedCloserFriendlyName A friendly name for the type of token expected for the scope closer + * to be used in the error message for failing tests. + * + * @dataProvider dataInMatchValue + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testInMatchValue($testMarker, $openerOffset, $closerOffset, $expectedCloserType, $expectedCloserFriendlyName) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, $openerOffset, $closerOffset, $expectedCloserFriendlyName); + + $this->assertSame($expectedCloserType, $tokens[($token + $closerOffset)]['type'], 'Mismatched scope closer type'); + + }//end testInMatchValue() + + + /** + * Data provider. + * + * @see testInMatchValue() + * + * @return array + */ + public function dataInMatchValue() + { + return [ + 'not_last_value' => [ + '/* testInMatchNotLastValue */', + 5, + 11, + 'T_COMMA', + 'comma', + ], + 'last_value_with_trailing_comma' => [ + '/* testInMatchLastValueWithTrailingComma */', + 5, + 11, + 'T_COMMA', + 'comma', + ], + 'last_value_without_trailing_comma_1' => [ + '/* testInMatchLastValueNoTrailingComma1 */', + 5, + 10, + 'T_CLOSE_PARENTHESIS', + 'close parenthesis', + ], + 'last_value_without_trailing_comma_2' => [ + '/* testInMatchLastValueNoTrailingComma2 */', + 5, + 11, + 'T_VARIABLE', + '$y variable', + ], + ]; + + }//end dataInMatchValue() + + + /** + * Test arrow function nested within a method declaration. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNestedInMethod() + { + $token = $this->getTargetToken('/* testNestedInMethod */', T_FN); + $this->backfillHelper($token); + $this->scopePositionTestHelper($token, 5, 17); + + }//end testNestedInMethod() + + + /** + * Verify that "fn" keywords which are not arrow functions get tokenized as T_STRING and don't + * have the extra token array indexes. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotAnArrowFunction + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNotAnArrowFunction($testMarker, $testContent='fn') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_STRING, T_FN], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame('T_STRING', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING'); + + $this->assertArrayNotHasKey('scope_condition', $tokenArray, 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokenArray, 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokenArray, 'Scope closer is set'); + $this->assertArrayNotHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is set'); + $this->assertArrayNotHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is set'); + $this->assertArrayNotHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is set'); + + }//end testNotAnArrowFunction() + + + /** + * Data provider. + * + * @see testNotAnArrowFunction() + * + * @return array + */ + public function dataNotAnArrowFunction() + { + return [ + ['/* testFunctionName */'], + [ + '/* testConstantDeclaration */', + 'FN', + ], + [ + '/* testConstantDeclarationLower */', + 'fn', + ], + ['/* testStaticMethodName */'], + ['/* testPropertyAssignment */'], + [ + '/* testAnonClassMethodName */', + 'fN', + ], + ['/* testNonArrowStaticMethodCall */'], + [ + '/* testNonArrowConstantAccess */', + 'FN', + ], + [ + '/* testNonArrowConstantAccessMixed */', + 'Fn', + ], + ['/* testNonArrowObjectMethodCall */'], + [ + '/* testNonArrowObjectMethodCallUpper */', + 'FN', + ], + [ + '/* testNonArrowNamespacedFunctionCall */', + 'Fn', + ], + ['/* testNonArrowNamespaceOperatorFunctionCall */'], + ['/* testNonArrowFunctionNameWithUnionTypes */'], + ['/* testLiveCoding */'], + ]; + + }//end dataNotAnArrowFunction() + + + /** + * Helper function to check that all token keys are correctly set for T_FN tokens. + * + * @param int $token The T_FN token to check. + * @param bool $skipScopeCloserCheck Whether to skip the scope closer check. + * This should be set to "true" when testing nested arrow functions, + * where the "inner" arrow function shares a scope closer with the + * "outer" arrow function, as the 'scope_condition' for the scope closer + * of the "inner" arrow function will point to the "outer" arrow function. + * + * @return void + */ + private function backfillHelper($token, $skipScopeCloserCheck=false) + { + $tokens = self::$phpcsFile->getTokens(); + + $this->assertTrue(array_key_exists('scope_condition', $tokens[$token]), 'Scope condition is not set'); + $this->assertTrue(array_key_exists('scope_opener', $tokens[$token]), 'Scope opener is not set'); + $this->assertTrue(array_key_exists('scope_closer', $tokens[$token]), 'Scope closer is not set'); + $this->assertSame($tokens[$token]['scope_condition'], $token, 'Scope condition is not the T_FN token'); + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$token]), 'Parenthesis owner is not set'); + $this->assertTrue(array_key_exists('parenthesis_opener', $tokens[$token]), 'Parenthesis opener is not set'); + $this->assertTrue(array_key_exists('parenthesis_closer', $tokens[$token]), 'Parenthesis closer is not set'); + $this->assertSame($tokens[$token]['parenthesis_owner'], $token, 'Parenthesis owner is not the T_FN token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertTrue(array_key_exists('scope_condition', $tokens[$opener]), 'Opener scope condition is not set'); + $this->assertTrue(array_key_exists('scope_opener', $tokens[$opener]), 'Opener scope opener is not set'); + $this->assertTrue(array_key_exists('scope_closer', $tokens[$opener]), 'Opener scope closer is not set'); + $this->assertSame($tokens[$opener]['scope_condition'], $token, 'Opener scope condition is not the T_FN token'); + $this->assertSame(T_FN_ARROW, $tokens[$opener]['code'], 'Arrow scope opener not tokenized as T_FN_ARROW (code)'); + $this->assertSame('T_FN_ARROW', $tokens[$opener]['type'], 'Arrow scope opener not tokenized as T_FN_ARROW (type)'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertTrue(array_key_exists('scope_condition', $tokens[$closer]), 'Closer scope condition is not set'); + $this->assertTrue(array_key_exists('scope_opener', $tokens[$closer]), 'Closer scope opener is not set'); + $this->assertTrue(array_key_exists('scope_closer', $tokens[$closer]), 'Closer scope closer is not set'); + if ($skipScopeCloserCheck === false) { + $this->assertSame($tokens[$closer]['scope_condition'], $token, 'Closer scope condition is not the T_FN token'); + } + + $opener = $tokens[$token]['parenthesis_opener']; + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$opener]), 'Opening parenthesis owner is not set'); + $this->assertSame($tokens[$opener]['parenthesis_owner'], $token, 'Opening parenthesis owner is not the T_FN token'); + + $closer = $tokens[$token]['parenthesis_closer']; + $this->assertTrue(array_key_exists('parenthesis_owner', $tokens[$closer]), 'Closing parenthesis owner is not set'); + $this->assertSame($tokens[$closer]['parenthesis_owner'], $token, 'Closing parenthesis owner is not the T_FN token'); + + }//end backfillHelper() + + + /** + * Helper function to check that the scope opener/closer positions are correctly set for T_FN tokens. + * + * @param int $token The T_FN token to check. + * @param int $openerOffset The expected offset of the scope opener in relation to + * the fn keyword. + * @param int $closerOffset The expected offset of the scope closer in relation to + * the fn keyword. + * @param string $expectedCloserType Optional. The type of token expected for the scope closer. + * + * @return void + */ + private function scopePositionTestHelper($token, $openerOffset, $closerOffset, $expectedCloserType='semicolon') + { + $tokens = self::$phpcsFile->getTokens(); + $expectedScopeOpener = ($token + $openerOffset); + $expectedScopeCloser = ($token + $closerOffset); + + $this->assertSame($expectedScopeOpener, $tokens[$token]['scope_opener'], 'Scope opener is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$token]['scope_closer'], 'Scope closer is not the '.$expectedCloserType.' token'); + + $opener = $tokens[$token]['scope_opener']; + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'Opener scope opener is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'Opener scope closer is not the '.$expectedCloserType.' token'); + + $closer = $tokens[$token]['scope_closer']; + $this->assertSame($expectedScopeOpener, $tokens[$closer]['scope_opener'], 'Closer scope opener is not the arrow token'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'Closer scope closer is not the '.$expectedCloserType.' token'); + + }//end scopePositionTestHelper() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.inc new file mode 100644 index 0000000..095a4d7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.inc @@ -0,0 +1,319 @@ + 'Zero', + 1 => 'One', + 2 => 'Two', + }; +} + +function matchNoTrailingComma($bool) { + /* testMatchNoTrailingComma */ + echo match ($bool) { + true => "true\n", + false => "false\n" + }; +} + +function matchWithDefault($i) { + /* testMatchWithDefault */ + return match ($i) { + 1 => 1, + 2 => 2, + default => 'default', + }; +} + +function matchExpressionInCondition($i) { + /* testMatchExpressionInCondition */ + return match (true) { + $i >= 50 => '50+', + $i >= 40 => '40-50', + $i >= 30 => '30-40', + $i >= 20 => '20-30', + $i >= 10 => '10-20', + default => '0-10', + }; +} + +function matchMultiCase($day) { + /* testMatchMultiCase */ + return match ($day) { + 1, 7 => false, + 2, 3, 4, 5, 6 => true, + }; +} + +function matchMultiCaseTrailingCommaInCase($bool) { + /* testMatchMultiCaseTrailingCommaInCase */ + echo match ($bool) { + false, + 0, + => "false\n", + true, + 1, + => "true\n", + default, + => "not bool\n", + }; +} + +assert((function () { + /* testMatchInClosureNotLowercase */ + Match ('foo') { + 'foo', 'bar' => false, + 'baz' => 'a', + default => 'b', + }; +})()); + +function matchInArrowFunction($x) { + /* testMatchInArrowFunction */ + $fn = fn($x) => match(true) { + 1, 2, 3, 4, 5 => 'foo', + default => 'bar', + }; +} + +function arrowFunctionInMatchNoTrailingComma($x) { + /* testArrowFunctionInMatchNoTrailingComma */ + return match ($x) { + 1 => fn($y) => callMe($y), + default => fn($y) => callThem($y) + }; +} + +/* testMatchInFunctionCallParamNotLowercase */ +var_dump(MATCH ( 'foo' ) { + 'foo' => dump_and_return('foo'), + 'bar' => dump_and_return('bar'), +}); + +/* testMatchInMethodCallParam */ +Test::usesValue(match(true) { true => $i }); + +/* testMatchDiscardResult */ +match (1) { + 1 => print "Executed\n", +}; + +/* testMatchWithDuplicateConditionsWithComments */ +echo match /*comment*/ ( $value /*comment*/ ) { + // Comment. + 2, 1 => '2, 1', + 1 => 1, + 3 => 3, + 4 => 4, + 5 => 5, +}; + +/* testNestedMatchOuter */ +$x = match ($y) { + /* testNestedMatchInner */ + default => match ($z) { 1 => 1 }, +}; + +/* testMatchInTernaryCondition */ +$x = match ($test) { 1 => 'a', 2 => 'b' } ? + /* testMatchInTernaryThen */ match ($test) { 1 => 'a', 2 => 'b' } : + /* testMatchInTernaryElse */ match ($notTest) { 3 => 'a', 4 => 'b' }; + +/* testMatchInArrayValue */ +$array = array( + match ($test) { 1 => 'a', 2 => 'b' }, +); + +/* testMatchInArrayKey */ +$array = [ + match ($test) { 1 => 'a', 2 => 'b' } => 'dynamic keys, woho!', +]; + +/* testMatchreturningArray */ +$matcher = match ($x) { + 0 => array( 0 => 1, 'a' => 2, 'b' => 3 ), + 1 => [1, 2, 3], + 2 => array( 1, [1, 2, 3], 2, 3), + 3 => [ 0 => 1, 'a' => array(1, 2, 3), 'b' => 2, 3], +}; + +/* testSwitchContainingMatch */ +switch ($something) { + /* testMatchWithDefaultNestedInSwitchCase1 */ + case 'foo': + $var = [1, 2, 3]; + $var = match ($i) { + 1 => 1, + default => 'default', + }; + continue 2; + + /* testMatchWithDefaultNestedInSwitchCase2 */ + case 'bar' ; + $i = callMe($a, $b); + return match ($i) { + 1 => 1, + default => 'default', + }; + + /* testMatchWithDefaultNestedInSwitchDefault */ + default: + echo 'something', match ($i) { + 1 => 1, + default => 'default', + }; + break; +} + +/* testMatchContainingSwitch */ +$x = match ($y) { + 5, 8 => function($z) { + /* testSwitchNestedInMatch1 */ + switch($z) { + case 'a': + $var = [1, 2, 3]; + return 'a'; + /* testSwitchDefaultNestedInMatchCase */ + default: + $i = callMe($a, $b); + return 'default1'; + } + }, + default => function($z) { + /* testSwitchNestedInMatch2 */ + switch($z) { + case 'a'; + $i = callMe($a, $b); + return 'b'; + /* testSwitchDefaultNestedInMatchDefault */ + default; + $var = [1, 2, 3]; + return 'default2'; + } + } +}; + +/* testMatchNoCases */ +// Intentional fatal error. +$x = match (true) {}; + +/* testMatchMultiDefault */ +// Intentional fatal error. +echo match (1) { + default => 'foo', + 1 => 'bar', + 2 => 'baz', + default => 'qux', +}; + +/* testNoMatchStaticMethodCall */ +$a = Foo::match($param); + +/* testNoMatchClassConstantAccess */ +$a = MyClass::MATCH; + +/* testNoMatchClassConstantArrayAccessMixedCase */ +$a = MyClass::Match[$a]; + +/* testNoMatchMethodCall */ +$a = $obj->match($param); + +/* testNoMatchMethodCallUpper */ +$a = $obj??->MATCH()->chain($param); + +/* testNoMatchPropertyAccess */ +$a = $obj->match; + +/* testNoMatchNamespacedFunctionCall */ +// Intentional fatal error. +$a = MyNS\Sub\match($param); + +/* testNoMatchNamespaceOperatorFunctionCall */ +// Intentional fatal error. +$a = namespace\match($param); + +interface MatchInterface { + /* testNoMatchInterfaceMethodDeclaration */ + public static function match($param); +} + +class MatchClass { + /* testNoMatchClassConstantDeclarationLower */ + const match = 'a'; + + /* testNoMatchClassMethodDeclaration */ + public static function match($param) { + /* testNoMatchPropertyAssignment */ + $this->match = 'a'; + } +} + +/* testNoMatchClassInstantiation */ +$obj = new Match(); + +$anon = new class() { + /* testNoMatchAnonClassMethodDeclaration */ + protected function maTCH($param) { + } +}; + +/* testNoMatchClassDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +class Match {} + +/* testNoMatchInterfaceDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +interface Match {} + +/* testNoMatchTraitDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +trait Match {} + +/* testNoMatchConstantDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +const MATCH = '1'; + +/* testNoMatchFunctionDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +function match() {} + +/* testNoMatchNamespaceDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +namespace Match {} + +/* testNoMatchExtendedClassDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +class Foo extends Match {} + +/* testNoMatchImplementedClassDeclaration */ +// Intentional fatal error. Match is now a reserved keyword. +class Bar implements Match {} + +/* testNoMatchInUseStatement */ +// Intentional fatal error in PHP < 8. Match is now a reserved keyword. +use Match\me; + +function brokenMatchNoCurlies($x) { + /* testNoMatchMissingCurlies */ + // Intentional fatal error. New control structure is not supported without curly braces. + return match ($x) + 0 => 'Zero', + 1 => 'One', + 2 => 'Two', + ; +} + +function brokenMatchAlternativeSyntax($x) { + /* testNoMatchAlternativeSyntax */ + // Intentional fatal error. Alternative syntax is not supported. + return match ($x) : + 0 => 'Zero', + 1 => 'One', + 2 => 'Two', + endmatch; +} + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +echo match diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.php new file mode 100644 index 0000000..72ca61e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillMatchTokenTest.php @@ -0,0 +1,529 @@ + + * @copyright 2020-2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class BackfillMatchTokenTest extends AbstractMethodUnitTest +{ + + + /** + * Test tokenization of match expressions. + * + * @param string $testMarker The comment prefacing the target token. + * @param int $openerOffset The expected offset of the scope opener in relation to the testMarker. + * @param int $closerOffset The expected offset of the scope closer in relation to the testMarker. + * @param string $testContent The token content to look for. + * + * @dataProvider dataMatchExpression + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testMatchExpression($testMarker, $openerOffset, $closerOffset, $testContent='match') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_STRING, T_MATCH], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_MATCH, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH (code)'); + $this->assertSame('T_MATCH', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH (type)'); + + $this->scopeTestHelper($token, $openerOffset, $closerOffset); + $this->parenthesisTestHelper($token); + + }//end testMatchExpression() + + + /** + * Data provider. + * + * @see testMatchExpression() + * + * @return array + */ + public function dataMatchExpression() + { + return [ + 'simple_match' => [ + '/* testMatchSimple */', + 6, + 33, + ], + 'no_trailing_comma' => [ + '/* testMatchNoTrailingComma */', + 6, + 24, + ], + 'with_default_case' => [ + '/* testMatchWithDefault */', + 6, + 33, + ], + 'expression_in_condition' => [ + '/* testMatchExpressionInCondition */', + 6, + 77, + ], + 'multicase' => [ + '/* testMatchMultiCase */', + 6, + 40, + ], + 'multicase_trailing_comma_in_case' => [ + '/* testMatchMultiCaseTrailingCommaInCase */', + 6, + 47, + ], + 'in_closure_not_lowercase' => [ + '/* testMatchInClosureNotLowercase */', + 6, + 36, + 'Match', + ], + 'in_arrow_function' => [ + '/* testMatchInArrowFunction */', + 5, + 36, + ], + 'arrow_function_in_match_no_trailing_comma' => [ + '/* testArrowFunctionInMatchNoTrailingComma */', + 6, + 44, + ], + 'in_function_call_param_not_lowercase' => [ + '/* testMatchInFunctionCallParamNotLowercase */', + 8, + 32, + 'MATCH', + ], + 'in_method_call_param' => [ + '/* testMatchInMethodCallParam */', + 5, + 13, + ], + 'discard_result' => [ + '/* testMatchDiscardResult */', + 6, + 18, + ], + 'duplicate_conditions_and_comments' => [ + '/* testMatchWithDuplicateConditionsWithComments */', + 12, + 59, + ], + 'nested_match_outer' => [ + '/* testNestedMatchOuter */', + 6, + 33, + ], + 'nested_match_inner' => [ + '/* testNestedMatchInner */', + 6, + 14, + ], + 'ternary_condition' => [ + '/* testMatchInTernaryCondition */', + 6, + 21, + ], + 'ternary_then' => [ + '/* testMatchInTernaryThen */', + 6, + 21, + ], + 'ternary_else' => [ + '/* testMatchInTernaryElse */', + 6, + 21, + ], + 'array_value' => [ + '/* testMatchInArrayValue */', + 6, + 21, + ], + 'array_key' => [ + '/* testMatchInArrayKey */', + 6, + 21, + ], + 'returning_array' => [ + '/* testMatchreturningArray */', + 6, + 125, + ], + 'nested_in_switch_case_1' => [ + '/* testMatchWithDefaultNestedInSwitchCase1 */', + 6, + 25, + ], + 'nested_in_switch_case_2' => [ + '/* testMatchWithDefaultNestedInSwitchCase2 */', + 6, + 25, + ], + 'nested_in_switch_default' => [ + '/* testMatchWithDefaultNestedInSwitchDefault */', + 6, + 25, + ], + 'match_with_nested_switch' => [ + '/* testMatchContainingSwitch */', + 6, + 180, + ], + 'no_cases' => [ + '/* testMatchNoCases */', + 6, + 7, + ], + 'multi_default' => [ + '/* testMatchMultiDefault */', + 6, + 40, + ], + ]; + + }//end dataMatchExpression() + + + /** + * Verify that "match" keywords which are not match control structures get tokenized as T_STRING + * and don't have the extra token array indexes. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotAMatchStructure + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNotAMatchStructure($testMarker, $testContent='match') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_STRING, T_MATCH], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_STRING, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (code)'); + $this->assertSame('T_STRING', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (type)'); + + $this->assertArrayNotHasKey('scope_condition', $tokenArray, 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokenArray, 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokenArray, 'Scope closer is set'); + $this->assertArrayNotHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is set'); + $this->assertArrayNotHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is set'); + $this->assertArrayNotHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is set'); + + $next = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($token + 1), null, true); + if ($next !== false && $tokens[$next]['code'] === T_OPEN_PARENTHESIS) { + $this->assertArrayNotHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is set for opener after'); + } + + }//end testNotAMatchStructure() + + + /** + * Data provider. + * + * @see testNotAMatchStructure() + * + * @return array + */ + public function dataNotAMatchStructure() + { + return [ + 'static_method_call' => ['/* testNoMatchStaticMethodCall */'], + 'class_constant_access' => [ + '/* testNoMatchClassConstantAccess */', + 'MATCH', + ], + 'class_constant_array_access' => [ + '/* testNoMatchClassConstantArrayAccessMixedCase */', + 'Match', + ], + 'method_call' => ['/* testNoMatchMethodCall */'], + 'method_call_uppercase' => [ + '/* testNoMatchMethodCallUpper */', + 'MATCH', + ], + 'property_access' => ['/* testNoMatchPropertyAccess */'], + 'namespaced_function_call' => ['/* testNoMatchNamespacedFunctionCall */'], + 'namespace_operator_function_call' => ['/* testNoMatchNamespaceOperatorFunctionCall */'], + 'interface_method_declaration' => ['/* testNoMatchInterfaceMethodDeclaration */'], + 'class_constant_declaration' => ['/* testNoMatchClassConstantDeclarationLower */'], + 'class_method_declaration' => ['/* testNoMatchClassMethodDeclaration */'], + 'property_assigment' => ['/* testNoMatchPropertyAssignment */'], + 'class_instantiation' => [ + '/* testNoMatchClassInstantiation */', + 'Match', + ], + 'anon_class_method_declaration' => [ + '/* testNoMatchAnonClassMethodDeclaration */', + 'maTCH', + ], + 'class_declaration' => [ + '/* testNoMatchClassDeclaration */', + 'Match', + ], + 'interface_declaration' => [ + '/* testNoMatchInterfaceDeclaration */', + 'Match', + ], + 'trait_declaration' => [ + '/* testNoMatchTraitDeclaration */', + 'Match', + ], + 'constant_declaration' => [ + '/* testNoMatchConstantDeclaration */', + 'MATCH', + ], + 'function_declaration' => ['/* testNoMatchFunctionDeclaration */'], + 'namespace_declaration' => [ + '/* testNoMatchNamespaceDeclaration */', + 'Match', + ], + 'class_extends_declaration' => [ + '/* testNoMatchExtendedClassDeclaration */', + 'Match', + ], + 'class_implements_declaration' => [ + '/* testNoMatchImplementedClassDeclaration */', + 'Match', + ], + 'use_statement' => [ + '/* testNoMatchInUseStatement */', + 'Match', + ], + 'unsupported_inline_control_structure' => ['/* testNoMatchMissingCurlies */'], + 'unsupported_alternative_syntax' => ['/* testNoMatchAlternativeSyntax */'], + 'live_coding' => ['/* testLiveCoding */'], + ]; + + }//end dataNotAMatchStructure() + + + /** + * Verify that the tokenization of switch structures is not affected by the backfill. + * + * @param string $testMarker The comment prefacing the target token. + * @param int $openerOffset The expected offset of the scope opener in relation to the testMarker. + * @param int $closerOffset The expected offset of the scope closer in relation to the testMarker. + * + * @dataProvider dataSwitchExpression + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testSwitchExpression($testMarker, $openerOffset, $closerOffset) + { + $token = $this->getTargetToken($testMarker, T_SWITCH); + + $this->scopeTestHelper($token, $openerOffset, $closerOffset); + $this->parenthesisTestHelper($token); + + }//end testSwitchExpression() + + + /** + * Data provider. + * + * @see testSwitchExpression() + * + * @return array + */ + public function dataSwitchExpression() + { + return [ + 'switch_containing_match' => [ + '/* testSwitchContainingMatch */', + 6, + 174, + ], + 'match_containing_switch_1' => [ + '/* testSwitchNestedInMatch1 */', + 5, + 63, + ], + 'match_containing_switch_2' => [ + '/* testSwitchNestedInMatch2 */', + 5, + 63, + ], + ]; + + }//end dataSwitchExpression() + + + /** + * Verify that the tokenization of a switch case/default structure containing a match structure + * or contained *in* a match structure is not affected by the backfill. + * + * @param string $testMarker The comment prefacing the target token. + * @param int $openerOffset The expected offset of the scope opener in relation to the testMarker. + * @param int $closerOffset The expected offset of the scope closer in relation to the testMarker. + * + * @dataProvider dataSwitchCaseVersusMatch + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testSwitchCaseVersusMatch($testMarker, $openerOffset, $closerOffset) + { + $token = $this->getTargetToken($testMarker, [T_CASE, T_DEFAULT]); + + $this->scopeTestHelper($token, $openerOffset, $closerOffset); + + }//end testSwitchCaseVersusMatch() + + + /** + * Data provider. + * + * @see testSwitchCaseVersusMatch() + * + * @return array + */ + public function dataSwitchCaseVersusMatch() + { + return [ + 'switch_with_nested_match_case_1' => [ + '/* testMatchWithDefaultNestedInSwitchCase1 */', + 3, + 55, + ], + 'switch_with_nested_match_case_2' => [ + '/* testMatchWithDefaultNestedInSwitchCase2 */', + 4, + 21, + ], + 'switch_with_nested_match_default_case' => [ + '/* testMatchWithDefaultNestedInSwitchDefault */', + 1, + 38, + ], + 'match_with_nested_switch_case' => [ + '/* testSwitchDefaultNestedInMatchCase */', + 1, + 18, + ], + 'match_with_nested_switch_default_case' => [ + '/* testSwitchDefaultNestedInMatchDefault */', + 1, + 20, + ], + ]; + + }//end dataSwitchCaseVersusMatch() + + + /** + * Helper function to verify that all scope related array indexes for a control structure + * are set correctly. + * + * @param string $token The control structure token to check. + * @param int $openerOffset The expected offset of the scope opener in relation to + * the control structure token. + * @param int $closerOffset The expected offset of the scope closer in relation to + * the control structure token. + * @param bool $skipScopeCloserCheck Whether to skip the scope closer check. + * This should be set to "true" when testing nested arrow functions, + * where the "inner" arrow function shares a scope closer with the + * "outer" arrow function, as the 'scope_condition' for the scope closer + * of the "inner" arrow function will point to the "outer" arrow function. + * + * @return void + */ + private function scopeTestHelper($token, $openerOffset, $closerOffset, $skipScopeCloserCheck=false) + { + $tokens = self::$phpcsFile->getTokens(); + $tokenArray = $tokens[$token]; + $tokenType = $tokenArray['type']; + $expectedScopeOpener = ($token + $openerOffset); + $expectedScopeCloser = ($token + $closerOffset); + + $this->assertArrayHasKey('scope_condition', $tokenArray, 'Scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokenArray, 'Scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokenArray, 'Scope closer is not set'); + $this->assertSame($token, $tokenArray['scope_condition'], 'Scope condition is not the '.$tokenType.' token'); + $this->assertSame($expectedScopeOpener, $tokenArray['scope_opener'], 'Scope opener of the '.$tokenType.' token incorrect'); + $this->assertSame($expectedScopeCloser, $tokenArray['scope_closer'], 'Scope closer of the '.$tokenType.' token incorrect'); + + $opener = $tokenArray['scope_opener']; + $this->assertArrayHasKey('scope_condition', $tokens[$opener], 'Opener scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokens[$opener], 'Opener scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokens[$opener], 'Opener scope closer is not set'); + $this->assertSame($token, $tokens[$opener]['scope_condition'], 'Opener scope condition is not the '.$tokenType.' token'); + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], $tokenType.' opener scope opener token incorrect'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], $tokenType.' opener scope closer token incorrect'); + + $closer = $tokenArray['scope_closer']; + $this->assertArrayHasKey('scope_condition', $tokens[$closer], 'Closer scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokens[$closer], 'Closer scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokens[$closer], 'Closer scope closer is not set'); + if ($skipScopeCloserCheck === false) { + $this->assertSame($token, $tokens[$closer]['scope_condition'], 'Closer scope condition is not the '.$tokenType.' token'); + } + + $this->assertSame($expectedScopeOpener, $tokens[$closer]['scope_opener'], $tokenType.' closer scope opener token incorrect'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], $tokenType.' closer scope closer token incorrect'); + + if (($opener + 1) !== $closer) { + for ($i = ($opener + 1); $i < $closer; $i++) { + $this->assertArrayHasKey( + $token, + $tokens[$i]['conditions'], + $tokenType.' condition not added for token belonging to the '.$tokenType.' structure' + ); + } + } + + }//end scopeTestHelper() + + + /** + * Helper function to verify that all parenthesis related array indexes for a control structure + * token are set correctly. + * + * @param int $token The position of the control structure token. + * + * @return void + */ + private function parenthesisTestHelper($token) + { + $tokens = self::$phpcsFile->getTokens(); + $tokenArray = $tokens[$token]; + $tokenType = $tokenArray['type']; + + $this->assertArrayHasKey('parenthesis_owner', $tokenArray, 'Parenthesis owner is not set'); + $this->assertArrayHasKey('parenthesis_opener', $tokenArray, 'Parenthesis opener is not set'); + $this->assertArrayHasKey('parenthesis_closer', $tokenArray, 'Parenthesis closer is not set'); + $this->assertSame($token, $tokenArray['parenthesis_owner'], 'Parenthesis owner is not the '.$tokenType.' token'); + + $opener = $tokenArray['parenthesis_opener']; + $this->assertArrayHasKey('parenthesis_owner', $tokens[$opener], 'Opening parenthesis owner is not set'); + $this->assertSame($token, $tokens[$opener]['parenthesis_owner'], 'Opening parenthesis owner is not the '.$tokenType.' token'); + + $closer = $tokenArray['parenthesis_closer']; + $this->assertArrayHasKey('parenthesis_owner', $tokens[$closer], 'Closing parenthesis owner is not set'); + $this->assertSame($token, $tokens[$closer]['parenthesis_owner'], 'Closing parenthesis owner is not the '.$tokenType.' token'); + + }//end parenthesisTestHelper() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillNumericSeparatorTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillNumericSeparatorTest.inc new file mode 100644 index 0000000..d855970 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillNumericSeparatorTest.inc @@ -0,0 +1,94 @@ + + * @copyright 2019 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BackfillNumericSeparatorTest extends AbstractMethodUnitTest +{ + + + /** + * Test that numbers using numeric separators are tokenized correctly. + * + * @param array $testData The data required for the specific test case. + * + * @dataProvider dataTestBackfill + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testBackfill($testData) + { + $tokens = self::$phpcsFile->getTokens(); + $number = $this->getTargetToken($testData['marker'], [T_LNUMBER, T_DNUMBER]); + + $this->assertSame(constant($testData['type']), $tokens[$number]['code']); + $this->assertSame($testData['type'], $tokens[$number]['type']); + $this->assertSame($testData['value'], $tokens[$number]['content']); + + }//end testBackfill() + + + /** + * Data provider. + * + * @see testBackfill() + * + * @return array + */ + public function dataTestBackfill() + { + $testHexType = 'T_LNUMBER'; + if (PHP_INT_MAX < 0xCAFEF00D) { + $testHexType = 'T_DNUMBER'; + } + + $testHexMultipleType = 'T_LNUMBER'; + if (PHP_INT_MAX < 0x42726F776E) { + $testHexMultipleType = 'T_DNUMBER'; + } + + $testIntMoreThanMaxType = 'T_LNUMBER'; + if (PHP_INT_MAX < 10223372036854775807) { + $testIntMoreThanMaxType = 'T_DNUMBER'; + } + + return [ + [ + [ + 'marker' => '/* testSimpleLNumber */', + 'type' => 'T_LNUMBER', + 'value' => '1_000_000_000', + ], + ], + [ + [ + 'marker' => '/* testSimpleDNumber */', + 'type' => 'T_DNUMBER', + 'value' => '107_925_284.88', + ], + ], + [ + [ + 'marker' => '/* testFloat */', + 'type' => 'T_DNUMBER', + 'value' => '6.674_083e-11', + ], + ], + [ + [ + 'marker' => '/* testFloat2 */', + 'type' => 'T_DNUMBER', + 'value' => '6.674_083e+11', + ], + ], + [ + [ + 'marker' => '/* testFloat3 */', + 'type' => 'T_DNUMBER', + 'value' => '1_2.3_4e1_23', + ], + ], + [ + [ + 'marker' => '/* testHex */', + 'type' => $testHexType, + 'value' => '0xCAFE_F00D', + ], + ], + [ + [ + 'marker' => '/* testHexMultiple */', + 'type' => $testHexMultipleType, + 'value' => '0x42_72_6F_77_6E', + ], + ], + [ + [ + 'marker' => '/* testHexInt */', + 'type' => 'T_LNUMBER', + 'value' => '0x42_72_6F', + ], + ], + [ + [ + 'marker' => '/* testBinary */', + 'type' => 'T_LNUMBER', + 'value' => '0b0101_1111', + ], + ], + [ + [ + 'marker' => '/* testOctal */', + 'type' => 'T_LNUMBER', + 'value' => '0137_041', + ], + ], + [ + [ + 'marker' => '/* testExplicitOctal */', + 'type' => 'T_LNUMBER', + 'value' => '0o137_041', + ], + ], + [ + [ + 'marker' => '/* testExplicitOctalCapitalised */', + 'type' => 'T_LNUMBER', + 'value' => '0O137_041', + ], + ], + [ + [ + 'marker' => '/* testIntMoreThanMax */', + 'type' => $testIntMoreThanMaxType, + 'value' => '10_223_372_036_854_775_807', + ], + ], + ]; + + }//end dataTestBackfill() + + + /** + * Test that numbers using numeric separators which are considered parse errors and/or + * which aren't relevant to the backfill, do not incorrectly trigger the backfill anyway. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param array $expectedTokens The token type and content of the expected token sequence. + * + * @dataProvider dataNoBackfill + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNoBackfill($testMarker, $expectedTokens) + { + $tokens = self::$phpcsFile->getTokens(); + $number = $this->getTargetToken($testMarker, [T_LNUMBER, T_DNUMBER]); + + foreach ($expectedTokens as $key => $expectedToken) { + $i = ($number + $key); + $this->assertSame($expectedToken['code'], $tokens[$i]['code']); + $this->assertSame($expectedToken['content'], $tokens[$i]['content']); + } + + }//end testNoBackfill() + + + /** + * Data provider. + * + * @see testBackfill() + * + * @return array + */ + public function dataNoBackfill() + { + return [ + [ + '/* testInvalid1 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '100', + ], + [ + 'code' => T_STRING, + 'content' => '_', + ], + ], + ], + [ + '/* testInvalid2 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '1', + ], + [ + 'code' => T_STRING, + 'content' => '__1', + ], + ], + ], + [ + '/* testInvalid3 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '1', + ], + [ + 'code' => T_STRING, + 'content' => '_', + ], + [ + 'code' => T_DNUMBER, + 'content' => '.0', + ], + ], + ], + [ + '/* testInvalid4 */', + [ + [ + 'code' => T_DNUMBER, + 'content' => '1.', + ], + [ + 'code' => T_STRING, + 'content' => '_0', + ], + ], + ], + [ + '/* testInvalid5 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '0', + ], + [ + 'code' => T_STRING, + 'content' => 'x_123', + ], + ], + ], + [ + '/* testInvalid6 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '0', + ], + [ + 'code' => T_STRING, + 'content' => 'b_101', + ], + ], + ], + [ + '/* testInvalid7 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '1', + ], + [ + 'code' => T_STRING, + 'content' => '_e2', + ], + ], + ], + [ + '/* testInvalid8 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '1', + ], + [ + 'code' => T_STRING, + 'content' => 'e_2', + ], + ], + ], + [ + '/* testInvalid9 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '107_925_284', + ], + [ + 'code' => T_WHITESPACE, + 'content' => ' ', + ], + [ + 'code' => T_DNUMBER, + 'content' => '.88', + ], + ], + ], + [ + '/* testInvalid10 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '107_925_284', + ], + [ + 'code' => T_COMMENT, + 'content' => '/*comment*/', + ], + [ + 'code' => T_DNUMBER, + 'content' => '.88', + ], + ], + ], + [ + '/* testInvalid11 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '0', + ], + [ + 'code' => T_STRING, + 'content' => 'o_137', + ], + ], + ], + [ + '/* testInvalid12 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '0', + ], + [ + 'code' => T_STRING, + 'content' => 'O_41', + ], + ], + ], + [ + '/* testCalc1 */', + [ + [ + 'code' => T_LNUMBER, + 'content' => '667_083', + ], + [ + 'code' => T_WHITESPACE, + 'content' => ' ', + ], + [ + 'code' => T_MINUS, + 'content' => '-', + ], + [ + 'code' => T_WHITESPACE, + 'content' => ' ', + ], + [ + 'code' => T_LNUMBER, + 'content' => '11', + ], + ], + ], + [ + '/* test Calc2 */', + [ + [ + 'code' => T_DNUMBER, + 'content' => '6.674_08e3', + ], + [ + 'code' => T_WHITESPACE, + 'content' => ' ', + ], + [ + 'code' => T_PLUS, + 'content' => '+', + ], + [ + 'code' => T_WHITESPACE, + 'content' => ' ', + ], + [ + 'code' => T_LNUMBER, + 'content' => '11', + ], + ], + ], + ]; + + }//end dataNoBackfill() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.inc new file mode 100644 index 0000000..1e66d46 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.inc @@ -0,0 +1,143 @@ +readonly = 'foo'; + + /* testReadonlyPropertyInTernaryOperator */ + $isReadonly = $this->readonly ? true : false; + } +} + +/* testReadonlyUsedAsFunctionName */ +function readonly() {} + +/* testReadonlyUsedAsFunctionNameWithReturnByRef */ +function &readonly() {} + +/* testReadonlyUsedAsNamespaceName */ +namespace Readonly; +/* testReadonlyUsedAsPartOfNamespaceName */ +namespace My\Readonly\Collection; +/* testReadonlyAsFunctionCall */ +$var = readonly($a, $b); +/* testReadonlyAsNamespacedFunctionCall */ +$var = My\NS\readonly($a, $b); +/* testReadonlyAsNamespaceRelativeFunctionCall */ +$var = namespace\ReadOnly($a, $b); +/* testReadonlyAsMethodCall */ +$var = $obj->readonly($a, $b); +/* testReadonlyAsNullsafeMethodCall */ +$var = $obj?->readOnly($a, $b); +/* testReadonlyAsStaticMethodCallWithSpace */ +$var = ClassName::readonly ($a, $b); +/* testClassConstantFetchWithReadonlyAsConstantName */ +echo ClassName::READONLY; + +/* testReadonlyUsedAsFunctionCallWithSpaceBetweenKeywordAndParens */ +$var = readonly /* comment */ (); + +// These test cases are inspired by +// https://github.com/php/php-src/commit/08b75395838b4b42a41e3c70684fa6c6b113eee0 +class ReadonlyWithDisjunctiveNormalForm +{ + /* testReadonlyPropertyDNFTypeUnqualified */ + readonly (B&C)|A $h; + + /* testReadonlyPropertyDNFTypeFullyQualified */ + public readonly (\Fully\Qualified\B&\Full\C)|\Foo\Bar $j; + + /* testReadonlyPropertyDNFTypePartiallyQualified */ + protected readonly (Partially\Qualified&C)|A $l; + + /* testReadonlyPropertyDNFTypeRelativeName */ + private readonly (namespace\Relative&C)|A $n; + + /* testReadonlyPropertyDNFTypeMultipleSets */ + private readonly (A&C)|(B&C)|(C&D) $m; + + /* testReadonlyPropertyDNFTypeWithArray */ + private readonly (B & C)|array $o; + + /* testReadonlyPropertyDNFTypeWithSpacesAndComments */ + private readonly ( B & C /*something*/) | A $q; + + public function __construct( + /* testReadonlyConstructorPropertyPromotionWithDNF */ + private readonly (B&C)|A $b1, + /* testReadonlyConstructorPropertyPromotionWithDNFAndRefence */ + readonly (B&C)|A &$b2, + ) {} + + /* testReadonlyUsedAsMethodNameWithDNFParam */ + public function readonly (A&B $param): void {} +} + +/* testParseErrorLiveCoding */ +// This must be the last test in the file. +readonly diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.php new file mode 100644 index 0000000..024220d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BackfillReadonlyTest.php @@ -0,0 +1,300 @@ + + * @copyright 2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BackfillReadonlyTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the "readonly" keyword is tokenized as such. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $testContent The token content to look for. + * + * @dataProvider dataReadonly + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testReadonly($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, [T_READONLY, T_STRING], $testContent); + $this->assertSame(T_READONLY, $tokens[$target]['code']); + $this->assertSame('T_READONLY', $tokens[$target]['type']); + + }//end testReadonly() + + + /** + * Data provider. + * + * @see testReadonly() + * + * @return array + */ + public function dataReadonly() + { + return [ + [ + '/* testReadonlyProperty */', + 'readonly', + ], + [ + '/* testVarReadonlyProperty */', + 'readonly', + ], + [ + '/* testReadonlyVarProperty */', + 'readonly', + ], + [ + '/* testStaticReadonlyProperty */', + 'readonly', + ], + [ + '/* testReadonlyStaticProperty */', + 'readonly', + ], + [ + '/* testConstReadonlyProperty */', + 'readonly', + ], + [ + '/* testReadonlyPropertyWithoutType */', + 'readonly', + ], + [ + '/* testPublicReadonlyProperty */', + 'readonly', + ], + [ + '/* testProtectedReadonlyProperty */', + 'readonly', + ], + [ + '/* testPrivateReadonlyProperty */', + 'readonly', + ], + [ + '/* testPublicReadonlyPropertyWithReadonlyFirst */', + 'readonly', + ], + [ + '/* testProtectedReadonlyPropertyWithReadonlyFirst */', + 'readonly', + ], + [ + '/* testPrivateReadonlyPropertyWithReadonlyFirst */', + 'readonly', + ], + [ + '/* testReadonlyWithCommentsInDeclaration */', + 'readonly', + ], + [ + '/* testReadonlyWithNullableProperty */', + 'readonly', + ], + [ + '/* testReadonlyNullablePropertyWithUnionTypeHintAndNullFirst */', + 'readonly', + ], + [ + '/* testReadonlyNullablePropertyWithUnionTypeHintAndNullLast */', + 'readonly', + ], + [ + '/* testReadonlyPropertyWithArrayTypeHint */', + 'readonly', + ], + [ + '/* testReadonlyPropertyWithSelfTypeHint */', + 'readonly', + ], + [ + '/* testReadonlyPropertyWithParentTypeHint */', + 'readonly', + ], + [ + '/* testReadonlyPropertyWithFullyQualifiedTypeHint */', + 'readonly', + ], + [ + '/* testReadonlyIsCaseInsensitive */', + 'ReAdOnLy', + ], + [ + '/* testReadonlyConstructorPropertyPromotion */', + 'readonly', + ], + [ + '/* testReadonlyConstructorPropertyPromotionWithReference */', + 'ReadOnly', + ], + [ + '/* testReadonlyPropertyInAnonymousClass */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeUnqualified */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeFullyQualified */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypePartiallyQualified */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeRelativeName */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeMultipleSets */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeWithArray */', + 'readonly', + ], + [ + '/* testReadonlyPropertyDNFTypeWithSpacesAndComments */', + 'readonly', + ], + [ + '/* testReadonlyConstructorPropertyPromotionWithDNF */', + 'readonly', + ], + [ + '/* testReadonlyConstructorPropertyPromotionWithDNFAndRefence */', + 'readonly', + ], + [ + '/* testParseErrorLiveCoding */', + 'readonly', + ], + ]; + + }//end dataReadonly() + + + /** + * Test that "readonly" when not used as the keyword is still tokenized as `T_STRING`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotReadonly + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNotReadonly($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, [T_READONLY, T_STRING], $testContent); + $this->assertSame(T_STRING, $tokens[$target]['code']); + $this->assertSame('T_STRING', $tokens[$target]['type']); + + }//end testNotReadonly() + + + /** + * Data provider. + * + * @see testNotReadonly() + * + * @return array + */ + public function dataNotReadonly() + { + return [ + [ + '/* testReadonlyUsedAsClassConstantName */', + 'READONLY', + ], + [ + '/* testReadonlyUsedAsMethodName */', + 'readonly', + ], + [ + '/* testReadonlyUsedAsPropertyName */', + 'readonly', + ], + [ + '/* testReadonlyPropertyInTernaryOperator */', + 'readonly', + ], + [ + '/* testReadonlyUsedAsFunctionName */', + 'readonly', + ], + [ + '/* testReadonlyUsedAsFunctionNameWithReturnByRef */', + 'readonly', + ], + [ + '/* testReadonlyUsedAsNamespaceName */', + 'Readonly', + ], + [ + '/* testReadonlyUsedAsPartOfNamespaceName */', + 'Readonly', + ], + [ + '/* testReadonlyAsFunctionCall */', + 'readonly', + ], + [ + '/* testReadonlyAsNamespacedFunctionCall */', + 'readonly', + ], + [ + '/* testReadonlyAsNamespaceRelativeFunctionCall */', + 'ReadOnly', + ], + [ + '/* testReadonlyAsMethodCall */', + 'readonly', + ], + [ + '/* testReadonlyAsNullsafeMethodCall */', + 'readOnly', + ], + [ + '/* testReadonlyAsStaticMethodCallWithSpace */', + 'readonly', + ], + [ + '/* testClassConstantFetchWithReadonlyAsConstantName */', + 'READONLY', + ], + [ + '/* testReadonlyUsedAsFunctionCallWithSpaceBetweenKeywordAndParens */', + 'readonly', + ], + [ + '/* testReadonlyUsedAsMethodNameWithDNFParam */', + 'readonly', + ], + ]; + + }//end dataNotReadonly() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.inc new file mode 100644 index 0000000..b758aba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.inc @@ -0,0 +1,146 @@ + $param | $int; + +/* testTypeUnionArrowReturnType */ +$arrowWithReturnType = fn ($param) : int|null => $param * 10; + +/* testBitwiseOrInArrayKey */ +$array = array( + A | B => /* testBitwiseOrInArrayValue */ B | C +); + +/* testBitwiseOrInShortArrayKey */ +$array = [ + A | B => /* testBitwiseOrInShortArrayValue */ B | C +]; + +/* testBitwiseOrTryCatch */ +try { +} catch ( ExceptionA | ExceptionB $e ) { +} + +/* testBitwiseOrNonArrowFnFunctionCall */ +$obj->fn($something | $else); + +/* testTypeUnionNonArrowFunctionDeclaration */ +function &fn(int|false $something) {} + +/* testTypeUnionPHP82TrueFirst */ +function trueTypeParam(true|null $param) {} + +/* testTypeUnionPHP82TrueMiddle */ +function trueTypeReturn($param): array|true|null {} + +/* testTypeUnionPHP82TrueLast */ +$closure = function ($param): array|true {} + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +return function( type| diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.php new file mode 100644 index 0000000..81e10e0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/BitwiseOrTest.php @@ -0,0 +1,142 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class BitwiseOrTest extends AbstractMethodUnitTest +{ + + + /** + * Test that non-union type bitwise or tokens are still tokenized as bitwise or. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataBitwiseOr + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testBitwiseOr($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_BITWISE_OR, T_TYPE_UNION]); + $this->assertSame(T_BITWISE_OR, $tokens[$opener]['code']); + $this->assertSame('T_BITWISE_OR', $tokens[$opener]['type']); + + }//end testBitwiseOr() + + + /** + * Data provider. + * + * @see testBitwiseOr() + * + * @return array + */ + public function dataBitwiseOr() + { + return [ + ['/* testBitwiseOr1 */'], + ['/* testBitwiseOr2 */'], + ['/* testBitwiseOrPropertyDefaultValue */'], + ['/* testBitwiseOrParamDefaultValue */'], + ['/* testBitwiseOr3 */'], + ['/* testBitwiseOrClosureParamDefault */'], + ['/* testBitwiseOrArrowParamDefault */'], + ['/* testBitwiseOrArrowExpression */'], + ['/* testBitwiseOrInArrayKey */'], + ['/* testBitwiseOrInArrayValue */'], + ['/* testBitwiseOrInShortArrayKey */'], + ['/* testBitwiseOrInShortArrayValue */'], + ['/* testBitwiseOrTryCatch */'], + ['/* testBitwiseOrNonArrowFnFunctionCall */'], + ['/* testLiveCoding */'], + ]; + + }//end dataBitwiseOr() + + + /** + * Test that bitwise or tokens when used as part of a union type are tokenized as `T_TYPE_UNION`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataTypeUnion + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testTypeUnion($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_BITWISE_OR, T_TYPE_UNION]); + $this->assertSame(T_TYPE_UNION, $tokens[$opener]['code']); + $this->assertSame('T_TYPE_UNION', $tokens[$opener]['type']); + + }//end testTypeUnion() + + + /** + * Data provider. + * + * @see testTypeUnion() + * + * @return array + */ + public function dataTypeUnion() + { + return [ + ['/* testTypeUnionPropertySimple */'], + ['/* testTypeUnionPropertyReverseModifierOrder */'], + ['/* testTypeUnionPropertyMulti1 */'], + ['/* testTypeUnionPropertyMulti2 */'], + ['/* testTypeUnionPropertyMulti3 */'], + ['/* testTypeUnionPropertyNamespaceRelative */'], + ['/* testTypeUnionPropertyPartiallyQualified */'], + ['/* testTypeUnionPropertyFullyQualified */'], + ['/* testTypeUnionPropertyWithReadOnlyKeyword */'], + ['/* testTypeUnionPropertyWithReadOnlyKeywordFirst */'], + ['/* testTypeUnionPropertyWithStaticAndReadOnlyKeywords */'], + ['/* testTypeUnionPropertyWithVarAndReadOnlyKeywords */'], + ['/* testTypeUnionPropertyWithOnlyReadOnlyKeyword */'], + ['/* testTypeUnionPropertyWithOnlyStaticKeyword */'], + ['/* testTypeUnionParam1 */'], + ['/* testTypeUnionParam2 */'], + ['/* testTypeUnionParam3 */'], + ['/* testTypeUnionParamNamespaceRelative */'], + ['/* testTypeUnionParamPartiallyQualified */'], + ['/* testTypeUnionParamFullyQualified */'], + ['/* testTypeUnionReturnType */'], + ['/* testTypeUnionConstructorPropertyPromotion */'], + ['/* testTypeUnionAbstractMethodReturnType1 */'], + ['/* testTypeUnionAbstractMethodReturnType2 */'], + ['/* testTypeUnionReturnTypeNamespaceRelative */'], + ['/* testTypeUnionReturnPartiallyQualified */'], + ['/* testTypeUnionReturnFullyQualified */'], + ['/* testTypeUnionClosureParamIllegalNullable */'], + ['/* testTypeUnionWithReference */'], + ['/* testTypeUnionWithSpreadOperator */'], + ['/* testTypeUnionClosureReturn */'], + ['/* testTypeUnionArrowParam */'], + ['/* testTypeUnionArrowReturnType */'], + ['/* testTypeUnionNonArrowFunctionDeclaration */'], + ['/* testTypeUnionPHP82TrueFirst */'], + ['/* testTypeUnionPHP82TrueMiddle */'], + ['/* testTypeUnionPHP82TrueLast */'], + ]; + + }//end dataTypeUnion() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.inc new file mode 100644 index 0000000..bc98c49 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.inc @@ -0,0 +1,264 @@ + 'a', + 2 => 'b', + /* testMatchDefaultIsKeyword */ default => 'default', +}; + +$closure = /* testFnIsKeyword */ fn () => 'string'; + +function () { + /* testYieldIsKeyword */ yield $f; + /* testYieldFromIsKeyword */ yield from someFunction(); +}; + +/* testDeclareIsKeyword */ declare(ticks=1): +/* testEndDeclareIsKeyword */ enddeclare; + +if (true /* testAndIsKeyword */ and false /* testOrIsKeyword */ or null /* testXorIsKeyword */ xor 0) { + +} + +$anonymousClass = new /* testAnonymousClassIsKeyword */ class {}; +$anonymousClass2 = new class /* testExtendsInAnonymousClassIsKeyword */ extends SomeParent {}; +$anonymousClass3 = new class /* testImplementsInAnonymousClassIsKeyword */ implements SomeInterface {}; + +$instantiated1 = new /* testClassInstantiationParentIsKeyword */ parent(); +$instantiated2 = new /* testClassInstantiationSelfIsKeyword */ SELF; +$instantiated3 = new /* testClassInstantiationStaticIsKeyword */ static($param); + +class Foo extends /* testNamespaceInNameIsKeyword */ namespace\Exception +{} + +function /* testKeywordAfterFunctionShouldBeString */ eval() {} +function /* testKeywordAfterFunctionByRefShouldBeString */ &switch() {} + +function /* testKeywordSelfAfterFunctionByRefShouldBeString */ &self() {} +function /* testKeywordStaticAfterFunctionByRefShouldBeString */ &static() {} +function /* testKeywordParentAfterFunctionByRefShouldBeString */ &parent() {} +function /* testKeywordFalseAfterFunctionByRefShouldBeString */ &false() {} +function /* testKeywordTrueAfterFunctionByRefShouldBeString */ & true () {} +function /* testKeywordNullAfterFunctionByRefShouldBeString */ &NULL() {} + +/* testKeywordAsFunctionCallNameShouldBeStringSelf */ self(); +/* testKeywordAsFunctionCallNameShouldBeStringStatic */ static(); +$obj-> /* testKeywordAsMethodCallNameShouldBeStringStatic */ static(); +/* testKeywordAsFunctionCallNameShouldBeStringParent */ parent(); +/* testKeywordAsFunctionCallNameShouldBeStringFalse */ false(); +/* testKeywordAsFunctionCallNameShouldBeStringTrue */ True (); +/* testKeywordAsFunctionCallNameShouldBeStringNull */ null /*comment*/ (); + +$instantiated4 = new /* testClassInstantiationFalseIsString */ False(); +$instantiated5 = new /* testClassInstantiationTrueIsString */ true (); +$instantiated6 = new /* testClassInstantiationNullIsString */ null(); + +$function = /* testStaticIsKeywordBeforeClosure */ static function(/* testStaticIsKeywordWhenParamType */ static $param) {}; +$arrow = /* testStaticIsKeywordBeforeArrow */ static fn(): /* testStaticIsKeywordWhenReturnType */ static => 10; + +function standAloneFalseTrueNullTypesAndMore( + /* testFalseIsKeywordAsParamType */ false $paramA, + /* testTrueIsKeywordAsParamType */ true $paramB, + /* testNullIsKeywordAsParamType */ null $paramC, +) /* testFalseIsKeywordAsReturnType */ false | /* testTrueIsKeywordAsReturnType */ true | /* testNullIsKeywordAsReturnType */ null { + if ($a === /* testFalseIsKeywordInComparison */ false + || $a === /* testTrueIsKeywordInComparison */ true + || $a === /* testNullIsKeywordInComparison */ null + ) {} +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.php new file mode 100644 index 0000000..2123351 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ContextSensitiveKeywordsTest.php @@ -0,0 +1,587 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class ContextSensitiveKeywordsTest extends AbstractMethodUnitTest +{ + + + /** + * Test that context sensitive keyword is tokenized as string when it should be string. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataStrings + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testStrings($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, (Tokens::$contextSensitiveKeywords + [T_STRING, T_NULL, T_FALSE, T_TRUE, T_PARENT, T_SELF])); + + $this->assertSame(T_STRING, $tokens[$token]['code']); + $this->assertSame('T_STRING', $tokens[$token]['type']); + + }//end testStrings() + + + /** + * Data provider. + * + * @see testStrings() + * + * @return array + */ + public function dataStrings() + { + return [ + ['/* testAbstract */'], + ['/* testArray */'], + ['/* testAs */'], + ['/* testBreak */'], + ['/* testCallable */'], + ['/* testCase */'], + ['/* testCatch */'], + ['/* testClass */'], + ['/* testClone */'], + ['/* testConst */'], + ['/* testContinue */'], + ['/* testDeclare */'], + ['/* testDefault */'], + ['/* testDo */'], + ['/* testEcho */'], + ['/* testElse */'], + ['/* testElseIf */'], + ['/* testEmpty */'], + ['/* testEndDeclare */'], + ['/* testEndFor */'], + ['/* testEndForeach */'], + ['/* testEndIf */'], + ['/* testEndSwitch */'], + ['/* testEndWhile */'], + ['/* testEnum */'], + ['/* testEval */'], + ['/* testExit */'], + ['/* testExtends */'], + ['/* testFinal */'], + ['/* testFinally */'], + ['/* testFn */'], + ['/* testFor */'], + ['/* testForeach */'], + ['/* testFunction */'], + ['/* testGlobal */'], + ['/* testGoto */'], + ['/* testIf */'], + ['/* testImplements */'], + ['/* testInclude */'], + ['/* testIncludeOnce */'], + ['/* testInstanceOf */'], + ['/* testInsteadOf */'], + ['/* testInterface */'], + ['/* testIsset */'], + ['/* testList */'], + ['/* testMatch */'], + ['/* testNamespace */'], + ['/* testNew */'], + ['/* testParent */'], + ['/* testPrint */'], + ['/* testPrivate */'], + ['/* testProtected */'], + ['/* testPublic */'], + ['/* testReadonly */'], + ['/* testRequire */'], + ['/* testRequireOnce */'], + ['/* testReturn */'], + ['/* testSelf */'], + ['/* testStatic */'], + ['/* testSwitch */'], + ['/* testThrows */'], + ['/* testTrait */'], + ['/* testTry */'], + ['/* testUnset */'], + ['/* testUse */'], + ['/* testVar */'], + ['/* testWhile */'], + ['/* testYield */'], + ['/* testYieldFrom */'], + ['/* testAnd */'], + ['/* testOr */'], + ['/* testXor */'], + ['/* testFalse */'], + ['/* testTrue */'], + ['/* testNull */'], + + ['/* testKeywordAfterNamespaceShouldBeString */'], + ['/* testNamespaceNameIsString1 */'], + ['/* testNamespaceNameIsString2 */'], + ['/* testNamespaceNameIsString3 */'], + + ['/* testKeywordAfterFunctionShouldBeString */'], + ['/* testKeywordAfterFunctionByRefShouldBeString */'], + ['/* testKeywordSelfAfterFunctionByRefShouldBeString */'], + ['/* testKeywordStaticAfterFunctionByRefShouldBeString */'], + ['/* testKeywordParentAfterFunctionByRefShouldBeString */'], + ['/* testKeywordFalseAfterFunctionByRefShouldBeString */'], + ['/* testKeywordTrueAfterFunctionByRefShouldBeString */'], + ['/* testKeywordNullAfterFunctionByRefShouldBeString */'], + + ['/* testKeywordAsFunctionCallNameShouldBeStringSelf */'], + ['/* testKeywordAsFunctionCallNameShouldBeStringStatic */'], + ['/* testKeywordAsMethodCallNameShouldBeStringStatic */'], + ['/* testKeywordAsFunctionCallNameShouldBeStringParent */'], + ['/* testKeywordAsFunctionCallNameShouldBeStringFalse */'], + ['/* testKeywordAsFunctionCallNameShouldBeStringTrue */'], + ['/* testKeywordAsFunctionCallNameShouldBeStringNull */'], + + ['/* testClassInstantiationFalseIsString */'], + ['/* testClassInstantiationTrueIsString */'], + ['/* testClassInstantiationNullIsString */'], + ]; + + }//end dataStrings() + + + /** + * Test that context sensitive keyword is tokenized as keyword when it should be keyword. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expectedTokenType The expected token type. + * + * @dataProvider dataKeywords + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testKeywords($testMarker, $expectedTokenType) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken( + $testMarker, + (Tokens::$contextSensitiveKeywords + [T_ANON_CLASS, T_MATCH_DEFAULT, T_PARENT, T_SELF, T_STRING, T_NULL, T_FALSE, T_TRUE]) + ); + + $this->assertSame(constant($expectedTokenType), $tokens[$token]['code']); + $this->assertSame($expectedTokenType, $tokens[$token]['type']); + + }//end testKeywords() + + + /** + * Data provider. + * + * @see testKeywords() + * + * @return array + */ + public function dataKeywords() + { + return [ + [ + '/* testNamespaceIsKeyword */', + 'T_NAMESPACE', + ], + [ + '/* testAbstractIsKeyword */', + 'T_ABSTRACT', + ], + [ + '/* testClassIsKeyword */', + 'T_CLASS', + ], + [ + '/* testExtendsIsKeyword */', + 'T_EXTENDS', + ], + [ + '/* testImplementsIsKeyword */', + 'T_IMPLEMENTS', + ], + [ + '/* testUseIsKeyword */', + 'T_USE', + ], + [ + '/* testInsteadOfIsKeyword */', + 'T_INSTEADOF', + ], + [ + '/* testAsIsKeyword */', + 'T_AS', + ], + [ + '/* testConstIsKeyword */', + 'T_CONST', + ], + [ + '/* testPrivateIsKeyword */', + 'T_PRIVATE', + ], + [ + '/* testProtectedIsKeyword */', + 'T_PROTECTED', + ], + [ + '/* testPublicIsKeyword */', + 'T_PUBLIC', + ], + [ + '/* testVarIsKeyword */', + 'T_VAR', + ], + [ + '/* testStaticIsKeyword */', + 'T_STATIC', + ], + [ + '/* testReadonlyIsKeyword */', + 'T_READONLY', + ], + [ + '/* testFinalIsKeyword */', + 'T_FINAL', + ], + [ + '/* testFunctionIsKeyword */', + 'T_FUNCTION', + ], + [ + '/* testCallableIsKeyword */', + 'T_CALLABLE', + ], + [ + '/* testSelfIsKeyword */', + 'T_SELF', + ], + [ + '/* testParentIsKeyword */', + 'T_PARENT', + ], + [ + '/* testReturnIsKeyword */', + 'T_RETURN', + ], + + [ + '/* testInterfaceIsKeyword */', + 'T_INTERFACE', + ], + [ + '/* testTraitIsKeyword */', + 'T_TRAIT', + ], + [ + '/* testEnumIsKeyword */', + 'T_ENUM', + ], + + [ + '/* testNewIsKeyword */', + 'T_NEW', + ], + [ + '/* testInstanceOfIsKeyword */', + 'T_INSTANCEOF', + ], + [ + '/* testCloneIsKeyword */', + 'T_CLONE', + ], + + [ + '/* testIfIsKeyword */', + 'T_IF', + ], + [ + '/* testEmptyIsKeyword */', + 'T_EMPTY', + ], + [ + '/* testElseIfIsKeyword */', + 'T_ELSEIF', + ], + [ + '/* testElseIsKeyword */', + 'T_ELSE', + ], + [ + '/* testEndIfIsKeyword */', + 'T_ENDIF', + ], + + [ + '/* testForIsKeyword */', + 'T_FOR', + ], + [ + '/* testEndForIsKeyword */', + 'T_ENDFOR', + ], + + [ + '/* testForeachIsKeyword */', + 'T_FOREACH', + ], + [ + '/* testEndForeachIsKeyword */', + 'T_ENDFOREACH', + ], + + [ + '/* testSwitchIsKeyword */', + 'T_SWITCH', + ], + [ + '/* testCaseIsKeyword */', + 'T_CASE', + ], + [ + '/* testDefaultIsKeyword */', + 'T_DEFAULT', + ], + [ + '/* testEndSwitchIsKeyword */', + 'T_ENDSWITCH', + ], + [ + '/* testBreakIsKeyword */', + 'T_BREAK', + ], + [ + '/* testContinueIsKeyword */', + 'T_CONTINUE', + ], + + [ + '/* testDoIsKeyword */', + 'T_DO', + ], + [ + '/* testWhileIsKeyword */', + 'T_WHILE', + ], + [ + '/* testEndWhileIsKeyword */', + 'T_ENDWHILE', + ], + + [ + '/* testTryIsKeyword */', + 'T_TRY', + ], + [ + '/* testThrowIsKeyword */', + 'T_THROW', + ], + [ + '/* testCatchIsKeyword */', + 'T_CATCH', + ], + [ + '/* testFinallyIsKeyword */', + 'T_FINALLY', + ], + + [ + '/* testGlobalIsKeyword */', + 'T_GLOBAL', + ], + [ + '/* testEchoIsKeyword */', + 'T_ECHO', + ], + [ + '/* testPrintIsKeyword */', + 'T_PRINT', + ], + [ + '/* testDieIsKeyword */', + 'T_EXIT', + ], + [ + '/* testEvalIsKeyword */', + 'T_EVAL', + ], + [ + '/* testExitIsKeyword */', + 'T_EXIT', + ], + [ + '/* testIssetIsKeyword */', + 'T_ISSET', + ], + [ + '/* testUnsetIsKeyword */', + 'T_UNSET', + ], + + [ + '/* testIncludeIsKeyword */', + 'T_INCLUDE', + ], + [ + '/* testIncludeOnceIsKeyword */', + 'T_INCLUDE_ONCE', + ], + [ + '/* testRequireIsKeyword */', + 'T_REQUIRE', + ], + [ + '/* testRequireOnceIsKeyword */', + 'T_REQUIRE_ONCE', + ], + + [ + '/* testListIsKeyword */', + 'T_LIST', + ], + [ + '/* testGotoIsKeyword */', + 'T_GOTO', + ], + [ + '/* testMatchIsKeyword */', + 'T_MATCH', + ], + [ + '/* testMatchDefaultIsKeyword */', + 'T_MATCH_DEFAULT', + ], + [ + '/* testFnIsKeyword */', + 'T_FN', + ], + + [ + '/* testYieldIsKeyword */', + 'T_YIELD', + ], + [ + '/* testYieldFromIsKeyword */', + 'T_YIELD_FROM', + ], + + [ + '/* testDeclareIsKeyword */', + 'T_DECLARE', + ], + [ + '/* testEndDeclareIsKeyword */', + 'T_ENDDECLARE', + ], + + [ + '/* testAndIsKeyword */', + 'T_LOGICAL_AND', + ], + [ + '/* testOrIsKeyword */', + 'T_LOGICAL_OR', + ], + [ + '/* testXorIsKeyword */', + 'T_LOGICAL_XOR', + ], + + [ + '/* testAnonymousClassIsKeyword */', + 'T_ANON_CLASS', + ], + [ + '/* testExtendsInAnonymousClassIsKeyword */', + 'T_EXTENDS', + ], + [ + '/* testImplementsInAnonymousClassIsKeyword */', + 'T_IMPLEMENTS', + ], + [ + '/* testClassInstantiationParentIsKeyword */', + 'T_PARENT', + ], + [ + '/* testClassInstantiationSelfIsKeyword */', + 'T_SELF', + ], + [ + '/* testClassInstantiationStaticIsKeyword */', + 'T_STATIC', + ], + [ + '/* testNamespaceInNameIsKeyword */', + 'T_NAMESPACE', + ], + + [ + '/* testStaticIsKeywordBeforeClosure */', + 'T_STATIC', + ], + [ + '/* testStaticIsKeywordWhenParamType */', + 'T_STATIC', + ], + [ + '/* testStaticIsKeywordBeforeArrow */', + 'T_STATIC', + ], + [ + '/* testStaticIsKeywordWhenReturnType */', + 'T_STATIC', + ], + + [ + '/* testFalseIsKeywordAsParamType */', + 'T_FALSE', + ], + [ + '/* testTrueIsKeywordAsParamType */', + 'T_TRUE', + ], + [ + '/* testNullIsKeywordAsParamType */', + 'T_NULL', + ], + [ + '/* testFalseIsKeywordAsReturnType */', + 'T_FALSE', + ], + [ + '/* testTrueIsKeywordAsReturnType */', + 'T_TRUE', + ], + [ + '/* testNullIsKeywordAsReturnType */', + 'T_NULL', + ], + [ + '/* testFalseIsKeywordInComparison */', + 'T_FALSE', + ], + [ + '/* testTrueIsKeywordInComparison */', + 'T_TRUE', + ], + [ + '/* testNullIsKeywordInComparison */', + 'T_NULL', + ], + ]; + + }//end dataKeywords() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.inc new file mode 100644 index 0000000..648149d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.inc @@ -0,0 +1,203 @@ + 1, + 2 => 2, + /* testSimpleMatchDefault */ + default => 'default', + }; +} + +function switchWithDefault($i) { + switch ($i) { + case 1: + return 1; + case 2: + return 2; + /* testSimpleSwitchDefault */ + default: + return 'default'; + } +} + +function switchWithDefaultAndCurlies($i) { + switch ($i) { + case 1: + return 1; + case 2: + return 2; + /* testSimpleSwitchDefaultWithCurlies */ + default: { + return 'default'; + } + } +} + +function matchWithDefaultInSwitch() { + switch ($something) { + case 'foo': + $var = [1, 2, 3]; + $var = match ($i) { + 1 => 1, + /* testMatchDefaultNestedInSwitchCase1 */ + default => 'default', + }; + continue; + + case 'bar' : + $i = callMe($a, $b); + return match ($i) { + 1 => 1, + /* testMatchDefaultNestedInSwitchCase2 */ + default => 'default', + }; + + /* testSwitchDefault */ + default; + echo 'something', match ($i) { + 1, => 1, + /* testMatchDefaultNestedInSwitchDefault */ + default, => 'default', + }; + break; + } +} + +function switchWithDefaultInMatch() { + $x = match ($y) { + 5, 8 => function($z) { + switch($z) { + case 'a'; + $var = [1, 2, 3]; + return 'a'; + /* testSwitchDefaultNestedInMatchCase */ + default: + $var = [1, 2, 3]; + return 'default1'; + } + }, + /* testMatchDefault */ + default => function($z) { + switch($z) { + case 'a': + $i = callMe($a, $b); + return 'b'; + /* testSwitchDefaultNestedInMatchDefault */ + default: + $i = callMe($a, $b); + return 'default2'; + } + } + }; +} + +function shortArrayWithConstantKey() { + $arr = [ + /* testClassConstantAsShortArrayKey */ + SomeClass::DEFAULT => 1, + /* testClassPropertyAsShortArrayKey */ + SomeClass->DEFAULT => 1, + /* testNamespacedConstantAsShortArrayKey */ + // Intentional parse error PHP < 8.0. Reserved keyword used as namespaced constant. + SomeNamespace\DEFAULT => 1, + /* testFQNGlobalConstantAsShortArrayKey */ + // Intentional parse error in PHP < 8.0. Reserved keyword used as global constant. + \DEFAULT => 1, + ]; +} + +function longArrayWithConstantKey() { + $arr = array( + /* testClassConstantAsLongArrayKey */ + SomeClass::DEFAULT => 1, + ); +} + +function yieldWithConstantKey() { + /* testClassConstantAsYieldKey */ + yield SomeClass::DEFAULT => 1; +} + +function longArrayWithConstantKeyNestedInMatch() { + return match($x) { + /* testMatchDefaultWithNestedLongArrayWithClassConstantKey */ + DEFAULT => array( + /* testClassConstantAsLongArrayKeyNestedInMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchDefaultWithNestedLongArrayWithClassConstantKeyLevelDown */ + DEFAULT => array( + /* testClassConstantAsLongArrayKeyNestedInMatchLevelDown */ + SomeClass::DEFAULT => 1, + ), + }, + ), + }; +} + +function shortArrayWithConstantKeyNestedInMatch() { + return match($x) { + /* testMatchDefaultWithNestedShortArrayWithClassConstantKey */ + DEFAULT => [ + /* testClassConstantAsShortArrayKeyNestedInMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchDefaultWithNestedShortArrayWithClassConstantKeyLevelDown */ + DEFAULT => [ + /* testClassConstantAsShortArrayKeyNestedInMatchLevelDown */ + SomeClass::DEFAULT => 1, + ], + }, + ], + }; +} + + +function longArrayWithConstantKeyWithNestedMatch() { + return array( + /* testClassConstantAsLongArrayKeyWithNestedMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchDefaultNestedInLongArray */ + DEFAULT => 'foo' + }, + ); +} + +function shortArrayWithConstantKeyWithNestedMatch() { + return [ + /* testClassConstantAsShortArrayKeyWithNestedMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchDefaultNestedInShortArray */ + DEFAULT => 'foo' + }, + ]; +} + +function switchWithConstantNonDefault($i) { + switch ($i) { + /* testClassConstantInSwitchCase */ + case SomeClass::DEFAULT: + return 1; + + /* testClassPropertyInSwitchCase */ + case SomeClass->DEFAULT: + return 2; + + /* testNamespacedConstantInSwitchCase */ + // Intentional parse error PHP < 8.0. Reserved keyword used as constant. + case SomeNamespace\DEFAULT: + return 2; + + /* testNamespaceRelativeConstantInSwitchCase */ + // Intentional parse error PHP < 8.0. Reserved keyword used as global constant. + case namespace\DEFAULT: + return 2; + } +} + +class Foo { + /* testClassConstant */ + const DEFAULT = 'foo'; + + /* testMethodDeclaration */ + public function default() {} +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.php new file mode 100644 index 0000000..c4d216d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DefaultKeywordTest.php @@ -0,0 +1,305 @@ + + * @copyright 2020-2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class DefaultKeywordTest extends AbstractMethodUnitTest +{ + + + /** + * Test the retokenization of the `default` keyword for match structure to `T_MATCH_DEFAULT`. + * + * Note: Cases and default structures within a match structure do *NOT* get case/default scope + * conditions, in contrast to case and default structures in switch control structures. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to look for. + * + * @dataProvider dataMatchDefault + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testMatchDefault($testMarker, $testContent='default') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_MATCH_DEFAULT, T_DEFAULT, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_MATCH_DEFAULT, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH_DEFAULT (code)'); + $this->assertSame('T_MATCH_DEFAULT', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH_DEFAULT (type)'); + + $this->assertArrayNotHasKey('scope_condition', $tokenArray, 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokenArray, 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokenArray, 'Scope closer is set'); + + }//end testMatchDefault() + + + /** + * Data provider. + * + * @see testMatchDefault() + * + * @return array + */ + public function dataMatchDefault() + { + return [ + 'simple_match_default' => ['/* testSimpleMatchDefault */'], + 'match_default_in_switch_case_1' => ['/* testMatchDefaultNestedInSwitchCase1 */'], + 'match_default_in_switch_case_2' => ['/* testMatchDefaultNestedInSwitchCase2 */'], + 'match_default_in_switch_default' => ['/* testMatchDefaultNestedInSwitchDefault */'], + 'match_default_containing_switch' => ['/* testMatchDefault */'], + + 'match_default_with_nested_long_array_and_default_key' => [ + '/* testMatchDefaultWithNestedLongArrayWithClassConstantKey */', + 'DEFAULT', + ], + 'match_default_with_nested_long_array_and_default_key_2' => [ + '/* testMatchDefaultWithNestedLongArrayWithClassConstantKeyLevelDown */', + 'DEFAULT', + ], + 'match_default_with_nested_short_array_and_default_key' => [ + '/* testMatchDefaultWithNestedShortArrayWithClassConstantKey */', + 'DEFAULT', + ], + 'match_default_with_nested_short_array_and_default_key_2' => [ + '/* testMatchDefaultWithNestedShortArrayWithClassConstantKeyLevelDown */', + 'DEFAULT', + ], + 'match_default_in_long_array' => [ + '/* testMatchDefaultNestedInLongArray */', + 'DEFAULT', + ], + 'match_default_in_short_array' => [ + '/* testMatchDefaultNestedInShortArray */', + 'DEFAULT', + ], + ]; + + }//end dataMatchDefault() + + + /** + * Verify that the retokenization of `T_DEFAULT` tokens in match constructs, doesn't negatively + * impact the tokenization of `T_DEFAULT` tokens in switch control structures. + * + * Note: Cases and default structures within a switch control structure *do* get case/default scope + * conditions. + * + * @param string $testMarker The comment prefacing the target token. + * @param int $openerOffset The expected offset of the scope opener in relation to the testMarker. + * @param int $closerOffset The expected offset of the scope closer in relation to the testMarker. + * @param int|null $conditionStop The expected offset at which tokens stop having T_DEFAULT as a scope condition. + * @param string $testContent The token content to look for. + * + * @dataProvider dataSwitchDefault + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testSwitchDefault($testMarker, $openerOffset, $closerOffset, $conditionStop=null, $testContent='default') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_MATCH_DEFAULT, T_DEFAULT, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + $expectedScopeOpener = ($token + $openerOffset); + $expectedScopeCloser = ($token + $closerOffset); + + $this->assertSame(T_DEFAULT, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_DEFAULT (code)'); + $this->assertSame('T_DEFAULT', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_DEFAULT (type)'); + + $this->assertArrayHasKey('scope_condition', $tokenArray, 'Scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokenArray, 'Scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokenArray, 'Scope closer is not set'); + $this->assertSame($token, $tokenArray['scope_condition'], 'Scope condition is not the T_DEFAULT token'); + $this->assertSame($expectedScopeOpener, $tokenArray['scope_opener'], 'Scope opener of the T_DEFAULT token incorrect'); + $this->assertSame($expectedScopeCloser, $tokenArray['scope_closer'], 'Scope closer of the T_DEFAULT token incorrect'); + + $opener = $tokenArray['scope_opener']; + $this->assertArrayHasKey('scope_condition', $tokens[$opener], 'Opener scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokens[$opener], 'Opener scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokens[$opener], 'Opener scope closer is not set'); + $this->assertSame($token, $tokens[$opener]['scope_condition'], 'Opener scope condition is not the T_DEFAULT token'); + $this->assertSame($expectedScopeOpener, $tokens[$opener]['scope_opener'], 'T_DEFAULT opener scope opener token incorrect'); + $this->assertSame($expectedScopeCloser, $tokens[$opener]['scope_closer'], 'T_DEFAULT opener scope closer token incorrect'); + + $closer = $tokenArray['scope_closer']; + $this->assertArrayHasKey('scope_condition', $tokens[$closer], 'Closer scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokens[$closer], 'Closer scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokens[$closer], 'Closer scope closer is not set'); + $this->assertSame($token, $tokens[$closer]['scope_condition'], 'Closer scope condition is not the T_DEFAULT token'); + $this->assertSame($expectedScopeOpener, $tokens[$closer]['scope_opener'], 'T_DEFAULT closer scope opener token incorrect'); + $this->assertSame($expectedScopeCloser, $tokens[$closer]['scope_closer'], 'T_DEFAULT closer scope closer token incorrect'); + + if (($opener + 1) !== $closer) { + $end = $closer; + if (isset($conditionStop) === true) { + $end = $conditionStop; + } + + for ($i = ($opener + 1); $i < $end; $i++) { + $this->assertArrayHasKey( + $token, + $tokens[$i]['conditions'], + 'T_DEFAULT condition not added for token belonging to the T_DEFAULT structure' + ); + } + } + + }//end testSwitchDefault() + + + /** + * Data provider. + * + * @see testSwitchDefault() + * + * @return array + */ + public function dataSwitchDefault() + { + return [ + 'simple_switch_default' => [ + '/* testSimpleSwitchDefault */', + 1, + 4, + ], + 'simple_switch_default_with_curlies' => [ + // For a default structure with curly braces, the scope opener + // will be the open curly and the closer the close curly. + // However, scope conditions will not be set for open to close, + // but only for the open token up to the "break/return/continue" etc. + '/* testSimpleSwitchDefaultWithCurlies */', + 3, + 12, + 6, + ], + 'switch_default_toplevel' => [ + '/* testSwitchDefault */', + 1, + 43, + ], + 'switch_default_nested_in_match_case' => [ + '/* testSwitchDefaultNestedInMatchCase */', + 1, + 20, + ], + 'switch_default_nested_in_match_default' => [ + '/* testSwitchDefaultNestedInMatchDefault */', + 1, + 18, + ], + ]; + + }//end dataSwitchDefault() + + + /** + * Verify that the retokenization of `T_DEFAULT` tokens in match constructs, doesn't negatively + * impact the tokenization of `T_STRING` tokens with the contents 'default' which aren't in + * actual fact the default keyword. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to look for. + * + * @dataProvider dataNotDefaultKeyword + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testNotDefaultKeyword($testMarker, $testContent='DEFAULT') + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_MATCH_DEFAULT, T_DEFAULT, T_STRING], $testContent); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_STRING, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (code)'); + $this->assertSame('T_STRING', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_STRING (type)'); + + $this->assertArrayNotHasKey('scope_condition', $tokenArray, 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokenArray, 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokenArray, 'Scope closer is set'); + + }//end testNotDefaultKeyword() + + + /** + * Data provider. + * + * @see testNotDefaultKeyword() + * + * @return array + */ + public function dataNotDefaultKeyword() + { + return [ + 'class-constant-as-short-array-key' => ['/* testClassConstantAsShortArrayKey */'], + 'class-property-as-short-array-key' => ['/* testClassPropertyAsShortArrayKey */'], + 'namespaced-constant-as-short-array-key' => ['/* testNamespacedConstantAsShortArrayKey */'], + 'fqn-global-constant-as-short-array-key' => ['/* testFQNGlobalConstantAsShortArrayKey */'], + 'class-constant-as-long-array-key' => ['/* testClassConstantAsLongArrayKey */'], + 'class-constant-as-yield-key' => ['/* testClassConstantAsYieldKey */'], + + 'class-constant-as-long-array-key-nested-in-match' => ['/* testClassConstantAsLongArrayKeyNestedInMatch */'], + 'class-constant-as-long-array-key-nested-in-match-2' => ['/* testClassConstantAsLongArrayKeyNestedInMatchLevelDown */'], + 'class-constant-as-short-array-key-nested-in-match' => ['/* testClassConstantAsShortArrayKeyNestedInMatch */'], + 'class-constant-as-short-array-key-nested-in-match-2' => ['/* testClassConstantAsShortArrayKeyNestedInMatchLevelDown */'], + 'class-constant-as-long-array-key-with-nested-match' => ['/* testClassConstantAsLongArrayKeyWithNestedMatch */'], + 'class-constant-as-short-array-key-with-nested-match' => ['/* testClassConstantAsShortArrayKeyWithNestedMatch */'], + + 'class-constant-in-switch-case' => ['/* testClassConstantInSwitchCase */'], + 'class-property-in-switch-case' => ['/* testClassPropertyInSwitchCase */'], + 'namespaced-constant-in-switch-case' => ['/* testNamespacedConstantInSwitchCase */'], + 'namespace-relative-constant-in-switch-case' => ['/* testNamespaceRelativeConstantInSwitchCase */'], + + 'class-constant-declaration' => ['/* testClassConstant */'], + 'class-method-declaration' => [ + '/* testMethodDeclaration */', + 'default', + ], + ]; + + }//end dataNotDefaultKeyword() + + + /** + * Test a specific edge case where a scope opener would be incorrectly set. + * + * @link https://github.com/squizlabs/PHP_CodeSniffer/issues/3326 + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testIssue3326() + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken('/* testClassConstant */', [T_SEMICOLON]); + $tokenArray = $tokens[$token]; + + $this->assertArrayNotHasKey('scope_condition', $tokenArray, 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokenArray, 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokenArray, 'Scope closer is set'); + + }//end testIssue3326() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.inc new file mode 100644 index 0000000..b67b066 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.inc @@ -0,0 +1,281 @@ + 'Zero', + ); +} + +function simpleShortArray($x) { + return [ + /* testShortArrayArrowSimple */ + 0 => 'Zero', + ]; +} + +function simpleLongList($x) { + list( + /* testLongListArrowSimple */ + 0 => $a, + ) = $x; +} + +function simpleShortList($x) { + [ + /* testShortListArrowSimple */ + 0 => $a, + ] = $x; +} + +function simpleYield($x) { + $i = 0; + foreach (explode("\n", $x) as $line) { + /* testYieldArrowSimple */ + yield ++$i => $line; + } +} + +function simpleForeach($x) { + /* testForeachArrowSimple */ + foreach ($x as $k => $value) {} +} + +function simpleMatch($x) { + return match ($x) { + /* testMatchArrowSimpleSingleCase */ + 0 => 'Zero', + /* testMatchArrowSimpleMultiCase */ + 2, 4, 6 => 'Zero', + /* testMatchArrowSimpleSingleCaseWithTrailingComma */ + 1, => 'Zero', + /* testMatchArrowSimpleMultiCaseWithTrailingComma */ + 3, 5, => 'Zero', + }; +} + +function simpleArrowFunction($y) { + /* testFnArrowSimple */ + return fn ($y) => callMe($y); +} + +function matchNestedInMatch() { + $x = match ($y) { + /* testMatchArrowNestedMatchOuter */ + default, => match ($z) { + /* testMatchArrowNestedMatchInner */ + 1 => 1 + }, + }; +} + +function matchNestedInLongArrayValue() { + $array = array( + /* testLongArrayArrowWithNestedMatchValue1 */ + 'a' => match ($test) { + /* testMatchArrowInLongArrayValue1 */ + 1 => 'a', + /* testMatchArrowInLongArrayValue2 */ + 2 => 'b' + }, + /* testLongArrayArrowWithNestedMatchValue2 */ + $i => match ($test) { + /* testMatchArrowInLongArrayValue3 */ + 1 => 'a', + }, + ); +} + +function matchNestedInShortArrayValue() { + $array = [ + /* testShortArrayArrowWithNestedMatchValue1 */ + 'a' => match ($test) { + /* testMatchArrowInShortArrayValue1 */ + 1 => 'a', + /* testMatchArrowInShortArrayValue2 */ + 2 => 'b' + }, + /* testShortArrayArrowWithNestedMatchValue2 */ + $i => match ($test) { + /* testMatchArrowInShortArrayValue3 */ + 1 => 'a', + }, + ]; +} + +function matchNestedInLongArrayKey() { + $array = array( + match ($test) { /* testMatchArrowInLongArrayKey1 */ 1 => 'a', /* testMatchArrowInLongArrayKey2 */ 2 => 'b' } + /* testLongArrayArrowWithMatchKey */ + => 'dynamic keys, woho!', + ); +} + +function matchNestedInShortArrayKey() { + $array = [ + match ($test) { /* testMatchArrowInShortArrayKey1 */ 1 => 'a', /* testMatchArrowInShortArrayKey2 */ 2 => 'b' } + /* testShortArrayArrowWithMatchKey */ + => 'dynamic keys, woho!', + ]; +} + +function arraysNestedInMatch() { + $matcher = match ($x) { + /* testMatchArrowWithLongArrayBodyWithKeys */ + 0 => array( + /* testLongArrayArrowInMatchBody1 */ + 0 => 1, + /* testLongArrayArrowInMatchBody2 */ + 'a' => 2, + /* testLongArrayArrowInMatchBody3 */ + 'b' => 3 + ), + /* testMatchArrowWithShortArrayBodyWithoutKeys */ + 1 => [1, 2, 3], + /* testMatchArrowWithLongArrayBodyWithoutKeys */ + 2 => array( 1, [1, 2, 3], 2, 3), + /* testMatchArrowWithShortArrayBodyWithKeys */ + 3 => [ + /* testShortArrayArrowInMatchBody1 */ + 0 => 1, + /* testShortArrayArrowInMatchBody2 */ + 'a' => array(1, 2, 3), + /* testShortArrayArrowInMatchBody3 */ + 'b' => 2, + 3 + ], + /* testShortArrayArrowinMatchCase1 */ + [4 => 'a', /* testShortArrayArrowinMatchCase2 */ 5 => 6] + /* testMatchArrowWithShortArrayWithKeysAsCase */ + => 'match with array as case value', + /* testShortArrayArrowinMatchCase3 */ + [4 => 'a'], /* testLongArrayArrowinMatchCase4 */ array(5 => 6), + /* testMatchArrowWithMultipleArraysWithKeysAsCase */ + => 'match with multiple arrays as case value', + }; +} + +function matchNestedInArrowFunction($x) { + /* testFnArrowWithMatchInValue */ + $fn = fn($x) => match(true) { + /* testMatchArrowInFnBody1 */ + 1, 2, 3, 4, 5 => 'foo', + /* testMatchArrowInFnBody2 */ + default => 'bar', + }; +} + +function arrowFunctionsNestedInMatch($x) { + return match ($x) { + /* testMatchArrowWithFnBody1 */ + 1 => /* testFnArrowInMatchBody1 */ fn($y) => callMe($y), + /* testMatchArrowWithFnBody2 */ + default => /* testFnArrowInMatchBody2 */ fn($y) => callThem($y) + }; +} + +function matchShortArrayMismash() { + $array = [ + match ($test) { + /* testMatchArrowInComplexShortArrayKey1 */ + 1 => [ /* testShortArrayArrowInComplexMatchValueinShortArrayKey */ 1 => 'a'], + /* testMatchArrowInComplexShortArrayKey2 */ + 2 => 'b' + /* testShortArrayArrowInComplexMatchArrayMismash */ + } => match ($test) { + /* testMatchArrowInComplexShortArrayValue1 */ + 1 => [ /* testShortArrayArrowInComplexMatchValueinShortArrayValue */ 1 => 'a'], + /* testMatchArrowInComplexShortArrayValue2 */ + 2 => /* testFnArrowInComplexMatchValueInShortArrayValue */ fn($y) => callMe($y) + }, + ]; +} + + +function longListInMatch($x, $y) { + return match($x) { + /* testMatchArrowWithLongListBody */ + 1 => list('a' => $a, /* testLongListArrowInMatchBody */ 'b' => $b, 'c' => list('d' => $c)) = $y, + /* testLongListArrowInMatchCase */ + list('a' => $a, 'b' => $b) = $y /* testMatchArrowWithLongListInCase */ => 'something' + }; +} + +function shortListInMatch($x, $y) { + return match($x) { + /* testMatchArrowWithShortListBody */ + 1 => ['a' => $a, 'b' => $b, 'c' => /* testShortListArrowInMatchBody */ ['d' => $c]] = $y, + /* testShortListArrowInMatchCase */ + ['a' => $a, 'b' => $b] = $y /* testMatchArrowWithShortListInCase */ => 'something' + }; +} + +function matchInLongList() { + /* testMatchArrowInLongListKey */ + list(match($x) {1 => 1, 2 => 2} /* testLongListArrowWithMatchInKey */ => $a) = $array; +} + +function matchInShortList() { + /* testMatchArrowInShortListKey */ + [match($x) {1 => 1, 2 => 2} /* testShortListArrowWithMatchInKey */ => $a] = $array; +} + +function longArrayWithConstantKey() { + $arr = array( + /* testLongArrayArrowWithClassConstantKey */ + SomeClass::DEFAULT => 1, + ); +} + +function shortArrayWithConstantKey() { + $arr = [ + /* testShortArrayArrowWithClassConstantKey */ + SomeClass::DEFAULT => 1, + ]; +} + +function yieldWithConstantKey() { + /* testYieldArrowWithClassConstantKey */ + yield SomeClass::DEFAULT => 1; +} + +function longArrayWithConstantKeyNestedInMatch() { + return match($x) { + /* testMatchArrowWithNestedLongArrayWithClassConstantKey */ + default => array( + /* testLongArrayArrowWithClassConstantKeyNestedInMatch */ + SomeClass::DEFAULT => 1, + ), + }; +} + +function shortArrayWithConstantKeyNestedInMatch() { + return match($x) { + /* testMatchArrowWithNestedShortArrayWithClassConstantKey */ + default => [ + /* testShortArrayArrowWithClassConstantKeyNestedInMatch */ + SomeClass::DEFAULT => 1, + ], + }; +} + + +function longArrayWithConstantKeyWithNestedMatch() { + return array( + /* testLongArrayArrowWithClassConstantKeyWithNestedMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchArrowNestedInLongArrayWithClassConstantKey */ + default => 'foo' + }, + ); +} + +function shortArrayWithConstantKeyWithNestedMatch() { + return [ + /* testShortArrayArrowWithClassConstantKeyWithNestedMatch */ + SomeClass::DEFAULT => match($x) { + /* testMatchArrowNestedInShortArrayWithClassConstantKey */ + default => 'foo' + }, + ]; +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.php new file mode 100644 index 0000000..e1a0174 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleArrowTest.php @@ -0,0 +1,237 @@ + + * @copyright 2020-2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class DoubleArrowTest extends AbstractMethodUnitTest +{ + + + /** + * Test that "normal" double arrows are correctly tokenized as `T_DOUBLE_ARROW`. + * + * @param string $testMarker The comment prefacing the target token. + * + * @dataProvider dataDoubleArrow + * @coversNothing + * + * @return void + */ + public function testDoubleArrow($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_DOUBLE_ARROW, T_MATCH_ARROW, T_FN_ARROW]); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_DOUBLE_ARROW, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_DOUBLE_ARROW (code)'); + $this->assertSame('T_DOUBLE_ARROW', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_DOUBLE_ARROW (type)'); + + }//end testDoubleArrow() + + + /** + * Data provider. + * + * @see testDoubleArrow() + * + * @return array + */ + public function dataDoubleArrow() + { + return [ + 'simple_long_array' => ['/* testLongArrayArrowSimple */'], + 'simple_short_array' => ['/* testShortArrayArrowSimple */'], + 'simple_long_list' => ['/* testLongListArrowSimple */'], + 'simple_short_list' => ['/* testShortListArrowSimple */'], + 'simple_yield' => ['/* testYieldArrowSimple */'], + 'simple_foreach' => ['/* testForeachArrowSimple */'], + + 'long_array_with_match_value_1' => ['/* testLongArrayArrowWithNestedMatchValue1 */'], + 'long_array_with_match_value_2' => ['/* testLongArrayArrowWithNestedMatchValue2 */'], + 'short_array_with_match_value_1' => ['/* testShortArrayArrowWithNestedMatchValue1 */'], + 'short_array_with_match_value_2' => ['/* testShortArrayArrowWithNestedMatchValue2 */'], + + 'long_array_with_match_key' => ['/* testLongArrayArrowWithMatchKey */'], + 'short_array_with_match_key' => ['/* testShortArrayArrowWithMatchKey */'], + + 'long_array_in_match_body_1' => ['/* testLongArrayArrowInMatchBody1 */'], + 'long_array_in_match_body_2' => ['/* testLongArrayArrowInMatchBody2 */'], + 'long_array_in_match_body_3' => ['/* testLongArrayArrowInMatchBody3 */'], + 'short_array_in_match_body_1' => ['/* testShortArrayArrowInMatchBody1 */'], + 'short_array_in_match_body_2' => ['/* testShortArrayArrowInMatchBody2 */'], + 'short_array_in_match_body_3' => ['/* testShortArrayArrowInMatchBody3 */'], + + 'short_array_in_match_case_1' => ['/* testShortArrayArrowinMatchCase1 */'], + 'short_array_in_match_case_2' => ['/* testShortArrayArrowinMatchCase2 */'], + 'short_array_in_match_case_3' => ['/* testShortArrayArrowinMatchCase3 */'], + 'long_array_in_match_case_4' => ['/* testLongArrayArrowinMatchCase4 */'], + + 'in_complex_short_array_key_match_value' => ['/* testShortArrayArrowInComplexMatchValueinShortArrayKey */'], + 'in_complex_short_array_toplevel' => ['/* testShortArrayArrowInComplexMatchArrayMismash */'], + 'in_complex_short_array_value_match_value' => ['/* testShortArrayArrowInComplexMatchValueinShortArrayValue */'], + + 'long_list_in_match_body' => ['/* testLongListArrowInMatchBody */'], + 'long_list_in_match_case' => ['/* testLongListArrowInMatchCase */'], + 'short_list_in_match_body' => ['/* testShortListArrowInMatchBody */'], + 'short_list_in_match_case' => ['/* testShortListArrowInMatchCase */'], + 'long_list_with_match_in_key' => ['/* testLongListArrowWithMatchInKey */'], + 'short_list_with_match_in_key' => ['/* testShortListArrowWithMatchInKey */'], + + 'long_array_with_constant_default_in_key' => ['/* testLongArrayArrowWithClassConstantKey */'], + 'short_array_with_constant_default_in_key' => ['/* testShortArrayArrowWithClassConstantKey */'], + 'yield_with_constant_default_in_key' => ['/* testYieldArrowWithClassConstantKey */'], + + 'long_array_with_default_in_key_in_match' => ['/* testLongArrayArrowWithClassConstantKeyNestedInMatch */'], + 'short_array_with_default_in_key_in_match' => ['/* testShortArrayArrowWithClassConstantKeyNestedInMatch */'], + 'long_array_with_default_in_key_with_match' => ['/* testLongArrayArrowWithClassConstantKeyWithNestedMatch */'], + 'short_array_with_default_in_key_with_match' => ['/* testShortArrayArrowWithClassConstantKeyWithNestedMatch */'], + ]; + + }//end dataDoubleArrow() + + + /** + * Test that double arrows in match expressions which are the demarkation between a case and the return value + * are correctly tokenized as `T_MATCH_ARROW`. + * + * @param string $testMarker The comment prefacing the target token. + * + * @dataProvider dataMatchArrow + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testMatchArrow($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_DOUBLE_ARROW, T_MATCH_ARROW, T_FN_ARROW]); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_MATCH_ARROW, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH_ARROW (code)'); + $this->assertSame('T_MATCH_ARROW', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_MATCH_ARROW (type)'); + + }//end testMatchArrow() + + + /** + * Data provider. + * + * @see testMatchArrow() + * + * @return array + */ + public function dataMatchArrow() + { + return [ + 'single_case' => ['/* testMatchArrowSimpleSingleCase */'], + 'multi_case' => ['/* testMatchArrowSimpleMultiCase */'], + 'single_case_with_trailing_comma' => ['/* testMatchArrowSimpleSingleCaseWithTrailingComma */'], + 'multi_case_with_trailing_comma' => ['/* testMatchArrowSimpleMultiCaseWithTrailingComma */'], + 'match_nested_outer' => ['/* testMatchArrowNestedMatchOuter */'], + 'match_nested_inner' => ['/* testMatchArrowNestedMatchInner */'], + + 'in_long_array_value_1' => ['/* testMatchArrowInLongArrayValue1 */'], + 'in_long_array_value_2' => ['/* testMatchArrowInLongArrayValue2 */'], + 'in_long_array_value_3' => ['/* testMatchArrowInLongArrayValue3 */'], + 'in_short_array_value_1' => ['/* testMatchArrowInShortArrayValue1 */'], + 'in_short_array_value_2' => ['/* testMatchArrowInShortArrayValue2 */'], + 'in_short_array_value_3' => ['/* testMatchArrowInShortArrayValue3 */'], + + 'in_long_array_key_1' => ['/* testMatchArrowInLongArrayKey1 */'], + 'in_long_array_key_2' => ['/* testMatchArrowInLongArrayKey2 */'], + 'in_short_array_key_1' => ['/* testMatchArrowInShortArrayKey1 */'], + 'in_short_array_key_2' => ['/* testMatchArrowInShortArrayKey2 */'], + + 'with_long_array_value_with_keys' => ['/* testMatchArrowWithLongArrayBodyWithKeys */'], + 'with_short_array_value_without_keys' => ['/* testMatchArrowWithShortArrayBodyWithoutKeys */'], + 'with_long_array_value_without_keys' => ['/* testMatchArrowWithLongArrayBodyWithoutKeys */'], + 'with_short_array_value_with_keys' => ['/* testMatchArrowWithShortArrayBodyWithKeys */'], + + 'with_short_array_with_keys_as_case' => ['/* testMatchArrowWithShortArrayWithKeysAsCase */'], + 'with_multiple_arrays_with_keys_as_case' => ['/* testMatchArrowWithMultipleArraysWithKeysAsCase */'], + + 'in_fn_body_case' => ['/* testMatchArrowInFnBody1 */'], + 'in_fn_body_default' => ['/* testMatchArrowInFnBody2 */'], + 'with_fn_body_case' => ['/* testMatchArrowWithFnBody1 */'], + 'with_fn_body_default' => ['/* testMatchArrowWithFnBody2 */'], + + 'in_complex_short_array_key_1' => ['/* testMatchArrowInComplexShortArrayKey1 */'], + 'in_complex_short_array_key_2' => ['/* testMatchArrowInComplexShortArrayKey2 */'], + 'in_complex_short_array_value_1' => ['/* testMatchArrowInComplexShortArrayValue1 */'], + 'in_complex_short_array_value_2' => ['/* testMatchArrowInComplexShortArrayValue2 */'], + + 'with_long_list_in_body' => ['/* testMatchArrowWithLongListBody */'], + 'with_long_list_in_case' => ['/* testMatchArrowWithLongListInCase */'], + 'with_short_list_in_body' => ['/* testMatchArrowWithShortListBody */'], + 'with_short_list_in_case' => ['/* testMatchArrowWithShortListInCase */'], + 'in_long_list_key' => ['/* testMatchArrowInLongListKey */'], + 'in_short_list_key' => ['/* testMatchArrowInShortListKey */'], + + 'with_long_array_value_with_default_key' => ['/* testMatchArrowWithNestedLongArrayWithClassConstantKey */'], + 'with_short_array_value_with_default_key' => ['/* testMatchArrowWithNestedShortArrayWithClassConstantKey */'], + 'in_long_array_value_with_default_key' => ['/* testMatchArrowNestedInLongArrayWithClassConstantKey */'], + 'in_short_array_value_with_default_key' => ['/* testMatchArrowNestedInShortArrayWithClassConstantKey */'], + ]; + + }//end dataMatchArrow() + + + /** + * Test that double arrows used as the scope opener for an arrow function + * are correctly tokenized as `T_FN_ARROW`. + * + * @param string $testMarker The comment prefacing the target token. + * + * @dataProvider dataFnArrow + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testFnArrow($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $token = $this->getTargetToken($testMarker, [T_DOUBLE_ARROW, T_MATCH_ARROW, T_FN_ARROW]); + $tokenArray = $tokens[$token]; + + $this->assertSame(T_FN_ARROW, $tokenArray['code'], 'Token tokenized as '.$tokenArray['type'].', not T_FN_ARROW (code)'); + $this->assertSame('T_FN_ARROW', $tokenArray['type'], 'Token tokenized as '.$tokenArray['type'].', not T_FN_ARROW (type)'); + + }//end testFnArrow() + + + /** + * Data provider. + * + * @see testFnArrow() + * + * @return array + */ + public function dataFnArrow() + { + return [ + 'simple_fn' => ['/* testFnArrowSimple */'], + + 'with_match_as_value' => ['/* testFnArrowWithMatchInValue */'], + 'in_match_value_case' => ['/* testFnArrowInMatchBody1 */'], + 'in_match_value_default' => ['/* testFnArrowInMatchBody2 */'], + + 'in_complex_match_value_in_short_array' => ['/* testFnArrowInComplexMatchValueInShortArrayValue */'], + ]; + + }//end dataFnArrow() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.inc new file mode 100644 index 0000000..62535b1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.inc @@ -0,0 +1,52 @@ +bar"; +/* testProperty2 */ +"{$foo->bar}"; + +/* testMethod1 */ +"{$foo->bar()}"; + +/* testClosure1 */ +"{$foo()}"; + +/* testChain1 */ +"{$foo['bar']->baz()()}"; + +/* testVariableVar1 */ +"${$bar}"; +/* testVariableVar2 */ +"${(foo)}"; +/* testVariableVar3 */ +"${foo->bar}"; + +/* testNested1 */ +"${foo["${bar}"]}"; +/* testNested2 */ +"${foo["${bar['baz']}"]}"; +/* testNested3 */ +"${foo->{$baz}}"; +/* testNested4 */ +"${foo->{${'a'}}}"; +/* testNested5 */ +"${foo->{"${'a'}"}}"; + +/* testParseError */ +"${foo["${bar diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.php new file mode 100644 index 0000000..4e837ba --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/DoubleQuotedStringTest.php @@ -0,0 +1,136 @@ + + * @copyright 2022 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class DoubleQuotedStringTest extends AbstractMethodUnitTest +{ + + + /** + * Test that double quoted strings contain the complete string. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expectedContent The expected content of the double quoted string. + * + * @dataProvider dataDoubleQuotedString + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testDoubleQuotedString($testMarker, $expectedContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, T_DOUBLE_QUOTED_STRING); + $this->assertSame($expectedContent, $tokens[$target]['content']); + + }//end testDoubleQuotedString() + + + /** + * Data provider. + * + * @see testDoubleQuotedString() + * + * @return array + */ + public function dataDoubleQuotedString() + { + return [ + [ + 'testMarker' => '/* testSimple1 */', + 'expectedContent' => '"$foo"', + ], + [ + 'testMarker' => '/* testSimple2 */', + 'expectedContent' => '"{$foo}"', + ], + [ + 'testMarker' => '/* testSimple3 */', + 'expectedContent' => '"${foo}"', + ], + [ + 'testMarker' => '/* testDIM1 */', + 'expectedContent' => '"$foo[bar]"', + ], + [ + 'testMarker' => '/* testDIM2 */', + 'expectedContent' => '"{$foo[\'bar\']}"', + ], + [ + 'testMarker' => '/* testDIM3 */', + 'expectedContent' => '"${foo[\'bar\']}"', + ], + [ + 'testMarker' => '/* testProperty1 */', + 'expectedContent' => '"$foo->bar"', + ], + [ + 'testMarker' => '/* testProperty2 */', + 'expectedContent' => '"{$foo->bar}"', + ], + [ + 'testMarker' => '/* testMethod1 */', + 'expectedContent' => '"{$foo->bar()}"', + ], + [ + 'testMarker' => '/* testClosure1 */', + 'expectedContent' => '"{$foo()}"', + ], + [ + 'testMarker' => '/* testChain1 */', + 'expectedContent' => '"{$foo[\'bar\']->baz()()}"', + ], + [ + 'testMarker' => '/* testVariableVar1 */', + 'expectedContent' => '"${$bar}"', + ], + [ + 'testMarker' => '/* testVariableVar2 */', + 'expectedContent' => '"${(foo)}"', + ], + [ + 'testMarker' => '/* testVariableVar3 */', + 'expectedContent' => '"${foo->bar}"', + ], + [ + 'testMarker' => '/* testNested1 */', + 'expectedContent' => '"${foo["${bar}"]}"', + ], + [ + 'testMarker' => '/* testNested2 */', + 'expectedContent' => '"${foo["${bar[\'baz\']}"]}"', + ], + [ + 'testMarker' => '/* testNested3 */', + 'expectedContent' => '"${foo->{$baz}}"', + ], + [ + 'testMarker' => '/* testNested4 */', + 'expectedContent' => '"${foo->{${\'a\'}}}"', + ], + [ + 'testMarker' => '/* testNested5 */', + 'expectedContent' => '"${foo->{"${\'a\'}"}}"', + ], + [ + 'testMarker' => '/* testParseError */', + 'expectedContent' => '"${foo["${bar +', + ], + ]; + + }//end dataDoubleQuotedString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/EnumCaseTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/EnumCaseTest.inc new file mode 100644 index 0000000..13b8724 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/EnumCaseTest.inc @@ -0,0 +1,95 @@ + + * @copyright 2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class EnumCaseTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the enum "case" is converted to T_ENUM_CASE. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataEnumCases + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testEnumCases($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $enumCase = $this->getTargetToken($testMarker, [T_ENUM_CASE, T_CASE]); + + $this->assertSame(T_ENUM_CASE, $tokens[$enumCase]['code']); + $this->assertSame('T_ENUM_CASE', $tokens[$enumCase]['type']); + + $this->assertArrayNotHasKey('scope_condition', $tokens[$enumCase], 'Scope condition is set'); + $this->assertArrayNotHasKey('scope_opener', $tokens[$enumCase], 'Scope opener is set'); + $this->assertArrayNotHasKey('scope_closer', $tokens[$enumCase], 'Scope closer is set'); + + }//end testEnumCases() + + + /** + * Data provider. + * + * @see testEnumCases() + * + * @return array + */ + public function dataEnumCases() + { + return [ + ['/* testPureEnumCase */'], + ['/* testBackingIntegerEnumCase */'], + ['/* testBackingStringEnumCase */'], + ['/* testEnumCaseInComplexEnum */'], + ['/* testEnumCaseIsCaseInsensitive */'], + ['/* testEnumCaseAfterSwitch */'], + ['/* testEnumCaseAfterSwitchWithEndSwitch */'], + ]; + + }//end dataEnumCases() + + + /** + * Test that "case" that is not enum case is still tokenized as `T_CASE`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataNotEnumCases + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testNotEnumCases($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $case = $this->getTargetToken($testMarker, [T_ENUM_CASE, T_CASE]); + + $this->assertSame(T_CASE, $tokens[$case]['code']); + $this->assertSame('T_CASE', $tokens[$case]['type']); + + $this->assertArrayHasKey('scope_condition', $tokens[$case], 'Scope condition is not set'); + $this->assertArrayHasKey('scope_opener', $tokens[$case], 'Scope opener is not set'); + $this->assertArrayHasKey('scope_closer', $tokens[$case], 'Scope closer is not set'); + + }//end testNotEnumCases() + + + /** + * Data provider. + * + * @see testNotEnumCases() + * + * @return array + */ + public function dataNotEnumCases() + { + return [ + ['/* testCaseWithSemicolonIsNotEnumCase */'], + ['/* testCaseWithConstantIsNotEnumCase */'], + ['/* testCaseWithConstantAndIdenticalIsNotEnumCase */'], + ['/* testCaseWithAssigmentToConstantIsNotEnumCase */'], + ['/* testIsNotEnumCaseIsCaseInsensitive */'], + ['/* testCaseInSwitchWhenCreatingEnumInSwitch1 */'], + ['/* testCaseInSwitchWhenCreatingEnumInSwitch2 */'], + ]; + + }//end dataNotEnumCases() + + + /** + * Test that "case" that is not enum case is still tokenized as `T_CASE`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataKeywordAsEnumCaseNameShouldBeString + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testKeywordAsEnumCaseNameShouldBeString($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $enumCaseName = $this->getTargetToken($testMarker, [T_STRING, T_INTERFACE, T_TRAIT, T_ENUM, T_FUNCTION, T_FALSE, T_DEFAULT, T_ARRAY]); + + $this->assertSame(T_STRING, $tokens[$enumCaseName]['code']); + $this->assertSame('T_STRING', $tokens[$enumCaseName]['type']); + + }//end testKeywordAsEnumCaseNameShouldBeString() + + + /** + * Data provider. + * + * @see testKeywordAsEnumCaseNameShouldBeString() + * + * @return array + */ + public function dataKeywordAsEnumCaseNameShouldBeString() + { + return [ + ['/* testKeywordAsEnumCaseNameShouldBeString1 */'], + ['/* testKeywordAsEnumCaseNameShouldBeString2 */'], + ['/* testKeywordAsEnumCaseNameShouldBeString3 */'], + ['/* testKeywordAsEnumCaseNameShouldBeString4 */'], + ]; + + }//end dataKeywordAsEnumCaseNameShouldBeString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.inc new file mode 100644 index 0000000..e65600b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.inc @@ -0,0 +1,40 @@ +finally = 'foo'; + } +} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.php new file mode 100644 index 0000000..d5e089a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/FinallyTest.php @@ -0,0 +1,96 @@ + + * @copyright 2021 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class FinallyTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the finally keyword is tokenized as such. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataFinallyKeyword + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testFinallyKeyword($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, [T_FINALLY, T_STRING]); + $this->assertSame(T_FINALLY, $tokens[$target]['code']); + $this->assertSame('T_FINALLY', $tokens[$target]['type']); + + }//end testFinallyKeyword() + + + /** + * Data provider. + * + * @see testFinallyKeyword() + * + * @return array + */ + public function dataFinallyKeyword() + { + return [ + ['/* testTryCatchFinally */'], + ['/* testTryFinallyCatch */'], + ['/* testTryFinally */'], + ]; + + }//end dataFinallyKeyword() + + + /** + * Test that 'finally' when not used as the reserved keyword is tokenized as `T_STRING`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataFinallyNonKeyword + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testFinallyNonKeyword($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, [T_FINALLY, T_STRING]); + $this->assertSame(T_STRING, $tokens[$target]['code']); + $this->assertSame('T_STRING', $tokens[$target]['type']); + + }//end testFinallyNonKeyword() + + + /** + * Data provider. + * + * @see testFinallyNonKeyword() + * + * @return array + */ + public function dataFinallyNonKeyword() + { + return [ + ['/* testFinallyUsedAsClassConstantName */'], + ['/* testFinallyUsedAsMethodName */'], + ['/* testFinallyUsedAsPropertyName */'], + ]; + + }//end dataFinallyNonKeyword() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.inc new file mode 100644 index 0000000..12df5d2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.inc @@ -0,0 +1,56 @@ + +
    + +property: + // Do something. + break; +} + +switch (true) { + /* testNotGotoDeclarationGlobalConstantInTernary */ + case $x === ($cond) ? CONST_A : CONST_B: + // Do something. + break; +} + +/* testNotGotoDeclarationEnumWithType */ +enum Suit: string implements Colorful, CardGame {} diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.php new file mode 100644 index 0000000..b4d1e8a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/GotoLabelTest.php @@ -0,0 +1,175 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class GotoLabelTest extends AbstractMethodUnitTest +{ + + + /** + * Verify that the label in a goto statement is tokenized as T_STRING. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to expect. + * + * @dataProvider dataGotoStatement + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testGotoStatement($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $label = $this->getTargetToken($testMarker, T_STRING); + + $this->assertTrue(is_int($label)); + $this->assertSame($testContent, $tokens[$label]['content']); + + }//end testGotoStatement() + + + /** + * Data provider. + * + * @see testGotoStatement() + * + * @return array + */ + public function dataGotoStatement() + { + return [ + [ + '/* testGotoStatement */', + 'marker', + ], + [ + '/* testGotoStatementInLoop */', + 'end', + ], + ]; + + }//end dataGotoStatement() + + + /** + * Verify that the label in a goto declaration is tokenized as T_GOTO_LABEL. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to expect. + * + * @dataProvider dataGotoDeclaration + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testGotoDeclaration($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $label = $this->getTargetToken($testMarker, T_GOTO_LABEL); + + $this->assertTrue(is_int($label)); + $this->assertSame($testContent, $tokens[$label]['content']); + + }//end testGotoDeclaration() + + + /** + * Data provider. + * + * @see testGotoDeclaration() + * + * @return array + */ + public function dataGotoDeclaration() + { + return [ + [ + '/* testGotoDeclaration */', + 'marker:', + ], + [ + '/* testGotoDeclarationOutsideLoop */', + 'end:', + ], + ]; + + }//end dataGotoDeclaration() + + + /** + * Verify that the constant used in a switch - case statement is not confused with a goto label. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $testContent The token content to expect. + * + * @dataProvider dataNotAGotoDeclaration + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNotAGotoDeclaration($testMarker, $testContent) + { + $tokens = self::$phpcsFile->getTokens(); + $target = $this->getTargetToken($testMarker, [T_GOTO_LABEL, T_STRING], $testContent); + + $this->assertSame(T_STRING, $tokens[$target]['code']); + $this->assertSame('T_STRING', $tokens[$target]['type']); + + }//end testNotAGotoDeclaration() + + + /** + * Data provider. + * + * @see testNotAGotoDeclaration() + * + * @return array + */ + public function dataNotAGotoDeclaration() + { + return [ + [ + '/* testNotGotoDeclarationGlobalConstant */', + 'CONSTANT', + ], + [ + '/* testNotGotoDeclarationNamespacedConstant */', + 'CONSTANT', + ], + [ + '/* testNotGotoDeclarationClassConstant */', + 'CONSTANT', + ], + [ + '/* testNotGotoDeclarationClassProperty */', + 'property', + ], + [ + '/* testNotGotoDeclarationGlobalConstantInTernary */', + 'CONST_A', + ], + [ + '/* testNotGotoDeclarationGlobalConstantInTernary */', + 'CONST_B', + ], + [ + '/* testNotGotoDeclarationEnumWithType */', + 'Suit', + ], + ]; + + }//end dataNotAGotoDeclaration() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocNowdocCloserTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocNowdocCloserTest.inc new file mode 100644 index 0000000..a800980 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocNowdocCloserTest.inc @@ -0,0 +1,43 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Files\DummyFile; +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +/** + * Heredoc/nowdoc closer token test. + * + * @requires PHP 7.3 + */ +class HeredocNowdocCloserTest extends AbstractMethodUnitTest +{ + + + /** + * Initialize & tokenize \PHP_CodeSniffer\Files\File with code from the test case file. + * + * {@internal This is a near duplicate of the original method. Only difference is that + * tab replacement is enabled for this test.} + * + * @beforeClass + * + * @return void + */ + public static function initializeFile() + { + $config = new Config(); + $config->standards = ['PSR1']; + $config->tabWidth = 4; + + $ruleset = new Ruleset($config); + + // Default to a file with the same name as the test class. Extension is property based. + $relativeCN = str_replace(__NAMESPACE__, '', get_called_class()); + $relativePath = str_replace('\\', DIRECTORY_SEPARATOR, $relativeCN); + $pathToTestFile = realpath(__DIR__).$relativePath.'.'.static::$fileExtension; + + // Make sure the file gets parsed correctly based on the file type. + $contents = 'phpcs_input_file: '.$pathToTestFile.PHP_EOL; + $contents .= file_get_contents($pathToTestFile); + + self::$phpcsFile = new DummyFile($contents, $ruleset, $config); + self::$phpcsFile->process(); + + }//end initializeFile() + + + /** + * Verify that leading (indent) whitespace in a heredoc/nowdoc closer token get the tab replacement treatment. + * + * @param string $testMarker The comment prefacing the target token. + * @param array $expected Expectations for the token array. + * + * @dataProvider dataHeredocNowdocCloserTabReplacement + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::createPositionMap + * + * @return void + */ + public function testHeredocNowdocCloserTabReplacement($testMarker, $expected) + { + $tokens = self::$phpcsFile->getTokens(); + + $closer = $this->getTargetToken($testMarker, [T_END_HEREDOC, T_END_NOWDOC]); + + foreach ($expected as $key => $value) { + if ($key === 'orig_content' && $value === null) { + $this->assertArrayNotHasKey($key, $tokens[$closer], "Unexpected 'orig_content' key found in the token array."); + continue; + } + + $this->assertArrayHasKey($key, $tokens[$closer], "Key $key not found in the token array."); + $this->assertSame($value, $tokens[$closer][$key], "Value for key $key does not match expectation."); + } + + }//end testHeredocNowdocCloserTabReplacement() + + + /** + * Data provider. + * + * @see testHeredocNowdocCloserTabReplacement() + * + * @return array + */ + public function dataHeredocNowdocCloserTabReplacement() + { + return [ + [ + 'testMarker' => '/* testHeredocCloserNoIndent */', + 'expected' => [ + 'length' => 3, + 'content' => 'EOD', + 'orig_content' => null, + ], + ], + [ + 'testMarker' => '/* testNowdocCloserNoIndent */', + 'expected' => [ + 'length' => 3, + 'content' => 'EOD', + 'orig_content' => null, + ], + ], + [ + 'testMarker' => '/* testHeredocCloserSpaceIndent */', + 'expected' => [ + 'length' => 7, + 'content' => ' END', + 'orig_content' => null, + ], + ], + [ + 'testMarker' => '/* testNowdocCloserSpaceIndent */', + 'expected' => [ + 'length' => 8, + 'content' => ' END', + 'orig_content' => null, + ], + ], + [ + 'testMarker' => '/* testHeredocCloserTabIndent */', + 'expected' => [ + 'length' => 8, + 'content' => ' END', + 'orig_content' => ' END', + ], + ], + [ + 'testMarker' => '/* testNowdocCloserTabIndent */', + 'expected' => [ + 'length' => 7, + 'content' => ' END', + 'orig_content' => ' END', + ], + ], + ]; + + }//end dataHeredocNowdocCloserTabReplacement() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.inc new file mode 100644 index 0000000..ae43e24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.inc @@ -0,0 +1,193 @@ +bar +EOD; + +/* testProperty2 */ +$heredoc = <<<"EOD" +{$foo->bar} +EOD; + +/* testMethod1 */ +$heredoc = <<bar()} +EOD; + +/* testClosure1 */ +$heredoc = <<<"EOD" +{$foo()} +EOD; + +/* testChain1 */ +$heredoc = <<baz()()} +EOD; + +/* testVariableVar1 */ +$heredoc = <<<"EOD" +${$bar} +EOD; + +/* testVariableVar2 */ +$heredoc = <<bar} +EOD; + +/* testNested1 */ +$heredoc = <<{$baz}} +EOD; + +/* testNested4 */ +$heredoc = <<<"EOD" +${foo->{${'a'}}} +EOD; + +/* testNested5 */ +$heredoc = <<{"${'a'}"}} +EOD; + +/* testSimple1Wrapped */ +$heredoc = <<bar Something +EOD; + +/* testProperty2Wrapped */ +$heredoc = <<<"EOD" +Do {$foo->bar} Something +EOD; + +/* testMethod1Wrapped */ +$heredoc = <<bar()} Something +EOD; + +/* testClosure1Wrapped */ +$heredoc = <<<"EOD" +Do {$foo()} Something +EOD; + +/* testChain1Wrapped */ +$heredoc = <<baz()()} Something +EOD; + +/* testVariableVar1Wrapped */ +$heredoc = <<<"EOD" +Do ${$bar} Something +EOD; + +/* testVariableVar2Wrapped */ +$heredoc = <<bar} Something +EOD; + +/* testNested1Wrapped */ +$heredoc = <<{$baz}} Something +EOD; + +/* testNested4Wrapped */ +$heredoc = <<<"EOD" +Do ${foo->{${'a'}}} Something +EOD; + +/* testNested5Wrapped */ +$heredoc = <<{"${'a'}"}} Something +EOD; diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.php new file mode 100644 index 0000000..993fd98 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/HeredocStringTest.php @@ -0,0 +1,153 @@ + + * @copyright 2022 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class HeredocStringTest extends AbstractMethodUnitTest +{ + + + /** + * Test that heredoc strings contain the complete interpolated string. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expectedContent The expected content of the heredoc string. + * + * @dataProvider dataHeredocString + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testHeredocString($testMarker, $expectedContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, T_HEREDOC); + $this->assertSame($expectedContent."\n", $tokens[$target]['content']); + + }//end testHeredocString() + + + /** + * Test that heredoc strings contain the complete interpolated string when combined with other texts. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param string $expectedContent The expected content of the heredoc string. + * + * @dataProvider dataHeredocString + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testHeredocStringWrapped($testMarker, $expectedContent) + { + $tokens = self::$phpcsFile->getTokens(); + + $testMarker = substr($testMarker, 0, -3).'Wrapped */'; + $target = $this->getTargetToken($testMarker, T_HEREDOC); + $this->assertSame('Do '.$expectedContent." Something\n", $tokens[$target]['content']); + + }//end testHeredocStringWrapped() + + + /** + * Data provider. + * + * @see testHeredocString() + * + * @return array + */ + public function dataHeredocString() + { + return [ + [ + 'testMarker' => '/* testSimple1 */', + 'expectedContent' => '$foo', + ], + [ + 'testMarker' => '/* testSimple2 */', + 'expectedContent' => '{$foo}', + ], + [ + 'testMarker' => '/* testSimple3 */', + 'expectedContent' => '${foo}', + ], + [ + 'testMarker' => '/* testDIM1 */', + 'expectedContent' => '$foo[bar]', + ], + [ + 'testMarker' => '/* testDIM2 */', + 'expectedContent' => '{$foo[\'bar\']}', + ], + [ + 'testMarker' => '/* testDIM3 */', + 'expectedContent' => '${foo[\'bar\']}', + ], + [ + 'testMarker' => '/* testProperty1 */', + 'expectedContent' => '$foo->bar', + ], + [ + 'testMarker' => '/* testProperty2 */', + 'expectedContent' => '{$foo->bar}', + ], + [ + 'testMarker' => '/* testMethod1 */', + 'expectedContent' => '{$foo->bar()}', + ], + [ + 'testMarker' => '/* testClosure1 */', + 'expectedContent' => '{$foo()}', + ], + [ + 'testMarker' => '/* testChain1 */', + 'expectedContent' => '{$foo[\'bar\']->baz()()}', + ], + [ + 'testMarker' => '/* testVariableVar1 */', + 'expectedContent' => '${$bar}', + ], + [ + 'testMarker' => '/* testVariableVar2 */', + 'expectedContent' => '${(foo)}', + ], + [ + 'testMarker' => '/* testVariableVar3 */', + 'expectedContent' => '${foo->bar}', + ], + [ + 'testMarker' => '/* testNested1 */', + 'expectedContent' => '${foo["${bar}"]}', + ], + [ + 'testMarker' => '/* testNested2 */', + 'expectedContent' => '${foo["${bar[\'baz\']}"]}', + ], + [ + 'testMarker' => '/* testNested3 */', + 'expectedContent' => '${foo->{$baz}}', + ], + [ + 'testMarker' => '/* testNested4 */', + 'expectedContent' => '${foo->{${\'a\'}}}', + ], + [ + 'testMarker' => '/* testNested5 */', + 'expectedContent' => '${foo->{"${\'a\'}"}}', + ], + ]; + + }//end dataHeredocString() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.inc new file mode 100644 index 0000000..b9c0df2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.inc @@ -0,0 +1,407 @@ +getPos(skip: false), + count: count(array_or_countable: $array), + value: 50 +); + +array_fill( + start_index: /* testNestedFunctionCallInner1 */ $obj->getPos(skip: false), + count: /* testNestedFunctionCallInner2 */ count(array_or_countable: $array), + value: 50 +); + +/* testNamespaceOperatorFunction */ +namespace\function_name(label:$string, more: false); + +/* testNamespaceRelativeFunction */ +Partially\Qualified\function_name(label:$string, more: false); + +/* testNamespacedFQNFunction */ +\Fully\Qualified\function_name(label: $string, more:false); + +/* testVariableFunction */ +$fn(label: $string, more:false); + +/* testVariableVariableFunction */ +${$fn}(label: $string, more:false); + +/* testMethodCall */ +$obj->methodName(label: $foo, more: $bar); + +/* testVariableMethodCall */ +$obj->{$var}(label: $foo, more: $bar); + +/* testClassInstantiation */ +$obj = new MyClass(label: $string, more:false); + +/* testClassInstantiationSelf */ +$obj = new self(label: $string, more:true); + +/* testClassInstantiationStatic */ +$obj = new static(label: $string, more:false); + +/* testAnonClass */ +$anon = new class(label: $string, more: false) { + public function __construct($label, $more) {} +}; + +function myfoo( $💩💩💩, $Пасха, $_valid) {} +/* testNonAsciiNames */ +foo(💩💩💩: [], Пасха: 'text', _valid: 123); + +/* testMixedPositionalAndNamedArgsWithTernary */ +foo( $cond ? true : false, name: $value2 ); + +/* testNamedArgWithTernary */ +foo( label: $cond ? true : false, more: $cond ? CONSTANT_A : CONSTANT_B ); + +/* testTernaryWithFunctionCallsInThenElse */ +echo $cond ? foo( label: $something ) : foo( more: $something_else ); + +/* testTernaryWithConstantsInThenElse */ +echo $cond ? CONSTANT_NAME : OTHER_CONSTANT; + +switch ($s) { + /* testSwitchCaseWithConstant */ + case MY_CONSTANT: + // Do something. + break; + + /* testSwitchCaseWithClassProperty */ + case $obj->property: + // Do something. + break; + + /* testSwitchDefault */ + default: + // Do something. + break; +} + +/* testTernaryWithClosuresAndReturnTypes */ +$closure = $cond ? function() : bool {return true;} : function() : int {return 123;}; + +/* testTernaryWithArrowFunctionsAndReturnTypes */ +$fn = $cond ? fn() : bool => true : fn() : int => 123; + + +/* testCompileErrorNamedBeforePositional */ +// Not the concern of PHPCS. Should still be handled. +test(param: $bar, $foo); + +/* testDuplicateName1 */ +// Error Exception, but not the concern of PHPCS. Should still be handled. +test(param: 1, /* testDuplicateName2 */ param: 2); + +/* testIncorrectOrderWithVariadic */ +// Error Exception, but not the concern of PHPCS. Should still be handled. +array_fill(start_index: 0, ...[100, 50]); + +/* testCompileErrorIncorrectOrderWithVariadic */ +// Not the concern of PHPCS. Should still be handled. +test(...$values, param: $value); // Compile-time error + +/* testParseErrorNoValue */ +// Not the concern of PHPCS. Should still be handled. +test(param1:, param2:); + +/* testParseErrorDynamicName */ +// Parse error. Ignore. +function_name($variableStoringParamName: $value); + +/* testParseErrorExit */ +// Exit is a language construct, not a function. Named params not supported, handle it anyway. +exit(status: $value); + +/* testParseErrorEmpty */ +// Empty is a language construct, not a function. Named params not supported, handle it anyway. +empty(variable: $value); + +/* testParseErrorEval */ +// Eval is a language construct, not a function. Named params not supported, handle it anyway. +eval(code: $value); + +/* testParseErrorArbitraryParentheses */ +// Parse error. Not named param, handle it anyway. +$calc = (something: $value / $other); + + +/* testReservedKeywordAbstract1 */ +foobar(abstract: $value, /* testReservedKeywordAbstract2 */ abstract: $value); + +/* testReservedKeywordAnd1 */ +foobar(and: $value, /* testReservedKeywordAnd2 */ and: $value); + +/* testReservedKeywordArray1 */ +foobar(array: $value, /* testReservedKeywordArray2 */ array: $value); + +/* testReservedKeywordAs1 */ +foobar(as: $value, /* testReservedKeywordAs2 */ as: $value); + +/* testReservedKeywordBreak1 */ +foobar(break: $value, /* testReservedKeywordBreak2 */ break: $value); + +/* testReservedKeywordCallable1 */ +foobar(callable: $value, /* testReservedKeywordCallable2 */ callable: $value); + +/* testReservedKeywordCase1 */ +foobar(case: $value, /* testReservedKeywordCase2 */ case: $value); + +/* testReservedKeywordCatch1 */ +foobar(catch: $value, /* testReservedKeywordCatch2 */ catch: $value); + +/* testReservedKeywordClass1 */ +foobar(class: $value, /* testReservedKeywordClass2 */ class: $value); + +/* testReservedKeywordClone1 */ +foobar(clone: $value, /* testReservedKeywordClone2 */ clone: $value); + +/* testReservedKeywordConst1 */ +foobar(const: $value, /* testReservedKeywordConst2 */ const: $value); + +/* testReservedKeywordContinue1 */ +foobar(continue: $value, /* testReservedKeywordContinue2 */ continue: $value); + +/* testReservedKeywordDeclare1 */ +foobar(declare: $value, /* testReservedKeywordDeclare2 */ declare: $value); + +/* testReservedKeywordDefault1 */ +foobar(default: $value, /* testReservedKeywordDefault2 */ default: $value); + +/* testReservedKeywordDie1 */ +foobar(die: $value, /* testReservedKeywordDie2 */ die: $value); + +/* testReservedKeywordDo1 */ +foobar(do: $value, /* testReservedKeywordDo2 */ do: $value); + +/* testReservedKeywordEcho1 */ +foobar(echo: $value, /* testReservedKeywordEcho2 */ echo: $value); + +/* testReservedKeywordElse1 */ +foobar(else: $value, /* testReservedKeywordElse2 */ else: $value); + +/* testReservedKeywordElseif1 */ +foobar(elseif: $value, /* testReservedKeywordElseif2 */ elseif: $value); + +/* testReservedKeywordEmpty1 */ +foobar(empty: $value, /* testReservedKeywordEmpty2 */ empty: $value); + +/* testReservedKeywordEnum1 */ +foobar(enum: $value, /* testReservedKeywordEnum2 */ enum: $value); + +/* testReservedKeywordEnddeclare1 */ +foobar(enddeclare: $value, /* testReservedKeywordEnddeclare2 */ enddeclare: $value); + +/* testReservedKeywordEndfor1 */ +foobar(endfor: $value, /* testReservedKeywordEndfor2 */ endfor: $value); + +/* testReservedKeywordEndforeach1 */ +foobar(endforeach: $value, /* testReservedKeywordEndforeach2 */ endforeach: $value); + +/* testReservedKeywordEndif1 */ +foobar(endif: $value, /* testReservedKeywordEndif2 */ endif: $value); + +/* testReservedKeywordEndswitch1 */ +foobar(endswitch: $value, /* testReservedKeywordEndswitch2 */ endswitch: $value); + +/* testReservedKeywordEndwhile1 */ +foobar(endwhile: $value, /* testReservedKeywordEndwhile2 */ endwhile: $value); + +/* testReservedKeywordEval1 */ +foobar(eval: $value, /* testReservedKeywordEval2 */ eval: $value); + +/* testReservedKeywordExit1 */ +foobar(exit: $value, /* testReservedKeywordExit2 */ exit: $value); + +/* testReservedKeywordExtends1 */ +foobar(extends: $value, /* testReservedKeywordExtends2 */ extends: $value); + +/* testReservedKeywordFinal1 */ +foobar(final: $value, /* testReservedKeywordFinal2 */ final: $value); + +/* testReservedKeywordFinally1 */ +foobar(finally: $value, /* testReservedKeywordFinally2 */ finally: $value); + +/* testReservedKeywordFn1 */ +foobar(fn: $value, /* testReservedKeywordFn2 */ fn: $value); + +/* testReservedKeywordFor1 */ +foobar(for: $value, /* testReservedKeywordFor2 */ for: $value); + +/* testReservedKeywordForeach1 */ +foobar(foreach: $value, /* testReservedKeywordForeach2 */ foreach: $value); + +/* testReservedKeywordFunction1 */ +foobar(function: $value, /* testReservedKeywordFunction2 */ function: $value); + +/* testReservedKeywordGlobal1 */ +foobar(global: $value, /* testReservedKeywordGlobal2 */ global: $value); + +/* testReservedKeywordGoto1 */ +foobar(goto: $value, /* testReservedKeywordGoto2 */ goto: $value); + +/* testReservedKeywordIf1 */ +foobar(if: $value, /* testReservedKeywordIf2 */ if: $value); + +/* testReservedKeywordImplements1 */ +foobar(implements: $value, /* testReservedKeywordImplements2 */ implements: $value); + +/* testReservedKeywordInclude1 */ +foobar(include: $value, /* testReservedKeywordInclude2 */ include: $value); + +/* testReservedKeywordInclude_once1 */ +foobar(include_once: $value, /* testReservedKeywordInclude_once2 */ include_once: $value); + +/* testReservedKeywordInstanceof1 */ +foobar(instanceof: $value, /* testReservedKeywordInstanceof2 */ instanceof: $value); + +/* testReservedKeywordInsteadof1 */ +foobar(insteadof: $value, /* testReservedKeywordInsteadof2 */ insteadof: $value); + +/* testReservedKeywordInterface1 */ +foobar(interface: $value, /* testReservedKeywordInterface2 */ interface: $value); + +/* testReservedKeywordIsset1 */ +foobar(isset: $value, /* testReservedKeywordIsset2 */ isset: $value); + +/* testReservedKeywordList1 */ +foobar(list: $value, /* testReservedKeywordList2 */ list: $value); + +/* testReservedKeywordMatch1 */ +foobar(match: $value, /* testReservedKeywordMatch2 */ match: $value); + +/* testReservedKeywordNamespace1 */ +foobar(namespace: $value, /* testReservedKeywordNamespace2 */ namespace: $value); + +/* testReservedKeywordNew1 */ +foobar(new: $value, /* testReservedKeywordNew2 */ new: $value); + +/* testReservedKeywordOr1 */ +foobar(or: $value, /* testReservedKeywordOr2 */ or: $value); + +/* testReservedKeywordPrint1 */ +foobar(print: $value, /* testReservedKeywordPrint2 */ print: $value); + +/* testReservedKeywordPrivate1 */ +foobar(private: $value, /* testReservedKeywordPrivate2 */ private: $value); + +/* testReservedKeywordProtected1 */ +foobar(protected: $value, /* testReservedKeywordProtected2 */ protected: $value); + +/* testReservedKeywordPublic1 */ +foobar(public: $value, /* testReservedKeywordPublic2 */ public: $value); + +/* testReservedKeywordReadonly1 */ +foobar(readonly: $value, /* testReservedKeywordReadonly2 */ readonly: $value); + +/* testReservedKeywordRequire1 */ +foobar(require: $value, /* testReservedKeywordRequire2 */ require: $value); + +/* testReservedKeywordRequire_once1 */ +foobar(require_once: $value, /* testReservedKeywordRequire_once2 */ require_once: $value); + +/* testReservedKeywordReturn1 */ +foobar(return: $value, /* testReservedKeywordReturn2 */ return: $value); + +/* testReservedKeywordStatic1 */ +foobar(static: $value, /* testReservedKeywordStatic2 */ static: $value); + +/* testReservedKeywordSwitch1 */ +foobar(switch: $value, /* testReservedKeywordSwitch2 */ switch: $value); + +/* testReservedKeywordThrow1 */ +foobar(throw: $value, /* testReservedKeywordThrow2 */ throw: $value); + +/* testReservedKeywordTrait1 */ +foobar(trait: $value, /* testReservedKeywordTrait2 */ trait: $value); + +/* testReservedKeywordTry1 */ +foobar(try: $value, /* testReservedKeywordTry2 */ try: $value); + +/* testReservedKeywordUnset1 */ +foobar(unset: $value, /* testReservedKeywordUnset2 */ unset: $value); + +/* testReservedKeywordUse1 */ +foobar(use: $value, /* testReservedKeywordUse2 */ use: $value); + +/* testReservedKeywordVar1 */ +foobar(var: $value, /* testReservedKeywordVar2 */ var: $value); + +/* testReservedKeywordWhile1 */ +foobar(while: $value, /* testReservedKeywordWhile2 */ while: $value); + +/* testReservedKeywordXor1 */ +foobar(xor: $value, /* testReservedKeywordXor2 */ xor: $value); + +/* testReservedKeywordYield1 */ +foobar(yield: $value, /* testReservedKeywordYield2 */ yield: $value); + +/* testReservedKeywordInt1 */ +foobar(int: $value, /* testReservedKeywordInt2 */ int: $value); + +/* testReservedKeywordFloat1 */ +foobar(float: $value, /* testReservedKeywordFloat2 */ float: $value); + +/* testReservedKeywordBool1 */ +foobar(bool: $value, /* testReservedKeywordBool2 */ bool: $value); + +/* testReservedKeywordString1 */ +foobar(string: $value, /* testReservedKeywordString2 */ string: $value); + +/* testReservedKeywordTrue1 */ +foobar(true: $value, /* testReservedKeywordTrue2 */ true: $value); + +/* testReservedKeywordFalse1 */ +foobar(false: $value, /* testReservedKeywordFalse2 */ false: $value); + +/* testReservedKeywordNull1 */ +foobar(null: $value, /* testReservedKeywordNull2 */ null: $value); + +/* testReservedKeywordVoid1 */ +foobar(void: $value, /* testReservedKeywordVoid2 */ void: $value); + +/* testReservedKeywordIterable1 */ +foobar(iterable: $value, /* testReservedKeywordIterable2 */ iterable: $value); + +/* testReservedKeywordObject1 */ +foobar(object: $value, /* testReservedKeywordObject2 */ object: $value); + +/* testReservedKeywordResource1 */ +foobar(resource: $value, /* testReservedKeywordResource2 */ resource: $value); + +/* testReservedKeywordMixed1 */ +foobar(mixed: $value, /* testReservedKeywordMixed2 */ mixed: $value); + +/* testReservedKeywordNumeric1 */ +foobar(numeric: $value, /* testReservedKeywordNumeric2 */ numeric: $value); + +/* testReservedKeywordParent1 */ +foobar(parent: $value, /* testReservedKeywordParent2 */ parent: $value); + +/* testReservedKeywordSelf1 */ +foobar(self: $value, /* testReservedKeywordSelf2 */ self: $value); + +/* testReservedKeywordNever1 */ +foobar(never: $value, /* testReservedKeywordNever2 */ never: $value); diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.php new file mode 100644 index 0000000..8819a20 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NamedFunctionCallArgumentsTest.php @@ -0,0 +1,885 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class NamedFunctionCallArgumentsTest extends AbstractMethodUnitTest +{ + + + /** + * Verify that parameter labels are tokenized as T_PARAM_NAME and that + * the colon after it is tokenized as a T_COLON. + * + * @param string $testMarker The comment prefacing the target token. + * @param array $parameters The token content for each parameter label to look for. + * + * @dataProvider dataNamedFunctionCallArguments + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNamedFunctionCallArguments($testMarker, $parameters) + { + $tokens = self::$phpcsFile->getTokens(); + + foreach ($parameters as $content) { + $label = $this->getTargetToken($testMarker, [T_STRING, T_PARAM_NAME], $content); + + $this->assertSame( + T_PARAM_NAME, + $tokens[$label]['code'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_PARAM_NAME (code)' + ); + $this->assertSame( + 'T_PARAM_NAME', + $tokens[$label]['type'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_PARAM_NAME (type)' + ); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + }//end foreach + + }//end testNamedFunctionCallArguments() + + + /** + * Data provider. + * + * @see testNamedFunctionCallArguments() + * + * @return array + */ + public function dataNamedFunctionCallArguments() + { + return [ + [ + '/* testNamedArgs */', + [ + 'start_index', + 'count', + 'value', + ], + ], + [ + '/* testNamedArgsMultiline */', + [ + 'start_index', + 'count', + 'value', + ], + ], + [ + '/* testNamedArgsWithWhitespaceAndComments */', + [ + 'start_index', + 'count', + 'value', + ], + ], + [ + '/* testMixedPositionalAndNamedArgs */', + ['double_encode'], + ], + [ + '/* testNestedFunctionCallOuter */', + [ + 'start_index', + 'count', + 'value', + ], + ], + [ + '/* testNestedFunctionCallInner1 */', + ['skip'], + ], + [ + '/* testNestedFunctionCallInner2 */', + ['array_or_countable'], + ], + [ + '/* testNamespaceOperatorFunction */', + [ + 'label', + 'more', + ], + ], + [ + '/* testNamespaceRelativeFunction */', + [ + 'label', + 'more', + ], + ], + [ + '/* testNamespacedFQNFunction */', + [ + 'label', + 'more', + ], + ], + [ + '/* testVariableFunction */', + [ + 'label', + 'more', + ], + ], + [ + '/* testVariableVariableFunction */', + [ + 'label', + 'more', + ], + ], + [ + '/* testMethodCall */', + [ + 'label', + 'more', + ], + ], + [ + '/* testVariableMethodCall */', + [ + 'label', + 'more', + ], + ], + [ + '/* testClassInstantiation */', + [ + 'label', + 'more', + ], + ], + [ + '/* testClassInstantiationSelf */', + [ + 'label', + 'more', + ], + ], + [ + '/* testClassInstantiationStatic */', + [ + 'label', + 'more', + ], + ], + [ + '/* testAnonClass */', + [ + 'label', + 'more', + ], + ], + [ + '/* testNonAsciiNames */', + [ + '💩💩💩', + 'Пасха', + '_valid', + ], + ], + + // Coding errors which should still be handled. + [ + '/* testCompileErrorNamedBeforePositional */', + ['param'], + ], + [ + '/* testDuplicateName1 */', + ['param'], + ], + [ + '/* testDuplicateName2 */', + ['param'], + ], + [ + '/* testIncorrectOrderWithVariadic */', + ['start_index'], + ], + [ + '/* testCompileErrorIncorrectOrderWithVariadic */', + ['param'], + ], + [ + '/* testParseErrorNoValue */', + [ + 'param1', + 'param2', + ], + ], + [ + '/* testParseErrorExit */', + ['status'], + ], + [ + '/* testParseErrorEmpty */', + ['variable'], + ], + [ + '/* testParseErrorEval */', + ['code'], + ], + [ + '/* testParseErrorArbitraryParentheses */', + ['something'], + ], + ]; + + }//end dataNamedFunctionCallArguments() + + + /** + * Verify that other T_STRING tokens within a function call are still tokenized as T_STRING. + * + * @param string $testMarker The comment prefacing the target token. + * @param string $content The token content to look for. + * + * @dataProvider dataOtherTstringInFunctionCall + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testOtherTstringInFunctionCall($testMarker, $content) + { + $tokens = self::$phpcsFile->getTokens(); + + $label = $this->getTargetToken($testMarker, [T_STRING, T_PARAM_NAME], $content); + + $this->assertSame( + T_STRING, + $tokens[$label]['code'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_STRING (code)' + ); + $this->assertSame( + 'T_STRING', + $tokens[$label]['type'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_STRING (type)' + ); + + }//end testOtherTstringInFunctionCall() + + + /** + * Data provider. + * + * @see testOtherTstringInFunctionCall() + * + * @return array + */ + public function dataOtherTstringInFunctionCall() + { + return [ + [ + '/* testPositionalArgs */', + 'START_INDEX', + ], + [ + '/* testPositionalArgs */', + 'COUNT', + ], + [ + '/* testPositionalArgs */', + 'VALUE', + ], + [ + '/* testNestedFunctionCallInner2 */', + 'count', + ], + ]; + + }//end dataOtherTstringInFunctionCall() + + + /** + * Verify whether the colons are tokenized correctly when a ternary is used in a mixed + * positional and named arguments function call. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testMixedPositionalAndNamedArgsWithTernary() + { + $tokens = self::$phpcsFile->getTokens(); + + $true = $this->getTargetToken('/* testMixedPositionalAndNamedArgsWithTernary */', T_TRUE); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($true + 1), null, true); + + $this->assertSame( + T_INLINE_ELSE, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (code)' + ); + $this->assertSame( + 'T_INLINE_ELSE', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (type)' + ); + + $label = $this->getTargetToken('/* testMixedPositionalAndNamedArgsWithTernary */', T_PARAM_NAME, 'name'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + }//end testMixedPositionalAndNamedArgsWithTernary() + + + /** + * Verify whether the colons are tokenized correctly when a ternary is used + * in a named arguments function call. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNamedArgWithTernary() + { + $tokens = self::$phpcsFile->getTokens(); + + /* + * First argument. + */ + + $label = $this->getTargetToken('/* testNamedArgWithTernary */', T_PARAM_NAME, 'label'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'First arg: Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'First arg: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'First arg: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + $true = $this->getTargetToken('/* testNamedArgWithTernary */', T_TRUE); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($true + 1), null, true); + + $this->assertSame( + T_INLINE_ELSE, + $tokens[$colon]['code'], + 'First arg ternary: Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (code)' + ); + $this->assertSame( + 'T_INLINE_ELSE', + $tokens[$colon]['type'], + 'First arg ternary: Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (type)' + ); + + /* + * Second argument. + */ + + $label = $this->getTargetToken('/* testNamedArgWithTernary */', T_PARAM_NAME, 'more'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Second arg: Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Second arg: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Second arg: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + $true = $this->getTargetToken('/* testNamedArgWithTernary */', T_STRING, 'CONSTANT_A'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($true + 1), null, true); + + $this->assertSame( + T_INLINE_ELSE, + $tokens[$colon]['code'], + 'Second arg ternary: Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (code)' + ); + $this->assertSame( + 'T_INLINE_ELSE', + $tokens[$colon]['type'], + 'Second arg ternary: Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (type)' + ); + + }//end testNamedArgWithTernary() + + + /** + * Verify whether the colons are tokenized correctly when named arguments + * function calls are used in a ternary. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testTernaryWithFunctionCallsInThenElse() + { + $tokens = self::$phpcsFile->getTokens(); + + /* + * Then. + */ + + $label = $this->getTargetToken('/* testTernaryWithFunctionCallsInThenElse */', T_PARAM_NAME, 'label'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Function in then: Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Function in then: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Function in then: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + $closeParens = $this->getTargetToken('/* testTernaryWithFunctionCallsInThenElse */', T_CLOSE_PARENTHESIS); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($closeParens + 1), null, true); + + $this->assertSame( + T_INLINE_ELSE, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (code)' + ); + $this->assertSame( + 'T_INLINE_ELSE', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (type)' + ); + + /* + * Else. + */ + + $label = $this->getTargetToken('/* testTernaryWithFunctionCallsInThenElse */', T_PARAM_NAME, 'more'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Function in else: Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Function in else: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Function in else: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + }//end testTernaryWithFunctionCallsInThenElse() + + + /** + * Verify whether the colons are tokenized correctly when constants are used in a ternary. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testTernaryWithConstantsInThenElse() + { + $tokens = self::$phpcsFile->getTokens(); + + $constant = $this->getTargetToken('/* testTernaryWithConstantsInThenElse */', T_STRING, 'CONSTANT_NAME'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($constant + 1), null, true); + + $this->assertSame( + T_INLINE_ELSE, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (code)' + ); + $this->assertSame( + 'T_INLINE_ELSE', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_INLINE_ELSE (type)' + ); + + }//end testTernaryWithConstantsInThenElse() + + + /** + * Verify whether the colons are tokenized correctly in a switch statement. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testSwitchStatement() + { + $tokens = self::$phpcsFile->getTokens(); + + $label = $this->getTargetToken('/* testSwitchCaseWithConstant */', T_STRING, 'MY_CONSTANT'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'First case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'First case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + $label = $this->getTargetToken('/* testSwitchCaseWithClassProperty */', T_STRING, 'property'); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Second case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Second case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + $default = $this->getTargetToken('/* testSwitchDefault */', T_DEFAULT); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($default + 1), null, true); + + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Default case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Default case: Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + }//end testSwitchStatement() + + + /** + * Verify that a variable parameter label (parse error) is still tokenized as T_VARIABLE. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testParseErrorVariableLabel() + { + $tokens = self::$phpcsFile->getTokens(); + + $label = $this->getTargetToken('/* testParseErrorDynamicName */', [T_VARIABLE, T_PARAM_NAME], '$variableStoringParamName'); + + $this->assertSame( + T_VARIABLE, + $tokens[$label]['code'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_VARIABLE (code)' + ); + $this->assertSame( + 'T_VARIABLE', + $tokens[$label]['type'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_VARIABLE (type)' + ); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + }//end testParseErrorVariableLabel() + + + /** + * Verify that reserved keywords used as a parameter label are tokenized as T_PARAM_NAME + * and that the colon after it is tokenized as a T_COLON. + * + * @param string $testMarker The comment prefacing the target token. + * @param array $tokenTypes The token codes to look for. + * @param string $tokenContent The token content to look for. + * + * @dataProvider dataReservedKeywordsAsName + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testReservedKeywordsAsName($testMarker, $tokenTypes, $tokenContent) + { + $tokens = self::$phpcsFile->getTokens(); + $label = $this->getTargetToken($testMarker, $tokenTypes, $tokenContent); + + $this->assertSame( + T_PARAM_NAME, + $tokens[$label]['code'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_PARAM_NAME (code)' + ); + $this->assertSame( + 'T_PARAM_NAME', + $tokens[$label]['type'], + 'Token tokenized as '.$tokens[$label]['type'].', not T_PARAM_NAME (type)' + ); + + // Get the next non-empty token. + $colon = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($label + 1), null, true); + + $this->assertSame( + ':', + $tokens[$colon]['content'], + 'Next token after parameter name is not a colon. Found: '.$tokens[$colon]['content'] + ); + $this->assertSame( + T_COLON, + $tokens[$colon]['code'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (code)' + ); + $this->assertSame( + 'T_COLON', + $tokens[$colon]['type'], + 'Token tokenized as '.$tokens[$colon]['type'].', not T_COLON (type)' + ); + + }//end testReservedKeywordsAsName() + + + /** + * Data provider. + * + * @see testReservedKeywordsAsName() + * + * @return array + */ + public function dataReservedKeywordsAsName() + { + $reservedKeywords = [ + // '__halt_compiler', NOT TESTABLE + 'abstract', + 'and', + 'array', + 'as', + 'break', + 'callable', + 'case', + 'catch', + 'class', + 'clone', + 'const', + 'continue', + 'declare', + 'default', + 'die', + 'do', + 'echo', + 'else', + 'elseif', + 'empty', + 'enddeclare', + 'endfor', + 'endforeach', + 'endif', + 'endswitch', + 'endwhile', + 'enum', + 'eval', + 'exit', + 'extends', + 'final', + 'finally', + 'fn', + 'for', + 'foreach', + 'function', + 'global', + 'goto', + 'if', + 'implements', + 'include', + 'include_once', + 'instanceof', + 'insteadof', + 'interface', + 'isset', + 'list', + 'match', + 'namespace', + 'new', + 'or', + 'print', + 'private', + 'protected', + 'public', + 'readonly', + 'require', + 'require_once', + 'return', + 'static', + 'switch', + 'throw', + 'trait', + 'try', + 'unset', + 'use', + 'var', + 'while', + 'xor', + 'yield', + 'int', + 'float', + 'bool', + 'string', + 'true', + 'false', + 'null', + 'void', + 'iterable', + 'object', + 'resource', + 'mixed', + 'numeric', + 'never', + + // Not reserved keyword, but do have their own token in PHPCS. + 'parent', + 'self', + ]; + + $data = []; + + foreach ($reservedKeywords as $keyword) { + $tokensTypes = [ + T_PARAM_NAME, + T_STRING, + T_GOTO_LABEL, + ]; + $tokenName = 'T_'.strtoupper($keyword); + + if ($keyword === 'and') { + $tokensTypes[] = T_LOGICAL_AND; + } else if ($keyword === 'die') { + $tokensTypes[] = T_EXIT; + } else if ($keyword === 'or') { + $tokensTypes[] = T_LOGICAL_OR; + } else if ($keyword === 'xor') { + $tokensTypes[] = T_LOGICAL_XOR; + } else if ($keyword === '__halt_compiler') { + $tokensTypes[] = T_HALT_COMPILER; + } else if (defined($tokenName) === true) { + $tokensTypes[] = constant($tokenName); + } + + $data[$keyword.'FirstParam'] = [ + '/* testReservedKeyword'.ucfirst($keyword).'1 */', + $tokensTypes, + $keyword, + ]; + + $data[$keyword.'SecondParam'] = [ + '/* testReservedKeyword'.ucfirst($keyword).'2 */', + $tokensTypes, + $keyword, + ]; + }//end foreach + + return $data; + + }//end dataReservedKeywordsAsName() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.inc new file mode 100644 index 0000000..982841e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.inc @@ -0,0 +1,29 @@ +foo; + +/* testNullsafeObjectOperator */ +echo $obj?->foo; + +/* testNullsafeObjectOperatorWriteContext */ +// Intentional parse error, but not the concern of the tokenizer. +$foo?->bar->baz = 'baz'; + +/* testTernaryThen */ +echo $obj ? $obj->prop : $other->prop; + +/* testParseErrorWhitespaceNotAllowed */ +echo $obj ? + -> foo; + +/* testParseErrorCommentNotAllowed */ +echo $obj ?/*comment*/-> foo; + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +echo $obj? diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.php new file mode 100644 index 0000000..83b48e6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/NullsafeObjectOperatorTest.php @@ -0,0 +1,140 @@ += 8.0 nullsafe object operator. + * + * @author Juliette Reinders Folmer + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class NullsafeObjectOperatorTest extends AbstractMethodUnitTest +{ + + /** + * Tokens to search for. + * + * @var array + */ + protected $find = [ + T_NULLSAFE_OBJECT_OPERATOR, + T_OBJECT_OPERATOR, + T_INLINE_THEN, + ]; + + + /** + * Test that a normal object operator is still tokenized as such. + * + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testObjectOperator() + { + $tokens = self::$phpcsFile->getTokens(); + + $operator = $this->getTargetToken('/* testObjectOperator */', $this->find); + $this->assertSame(T_OBJECT_OPERATOR, $tokens[$operator]['code'], 'Failed asserting code is object operator'); + $this->assertSame('T_OBJECT_OPERATOR', $tokens[$operator]['type'], 'Failed asserting type is object operator'); + + }//end testObjectOperator() + + + /** + * Test that a nullsafe object operator is tokenized as such. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataNullsafeObjectOperator + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testNullsafeObjectOperator($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $operator = $this->getTargetToken($testMarker, $this->find); + $this->assertSame(T_NULLSAFE_OBJECT_OPERATOR, $tokens[$operator]['code'], 'Failed asserting code is nullsafe object operator'); + $this->assertSame('T_NULLSAFE_OBJECT_OPERATOR', $tokens[$operator]['type'], 'Failed asserting type is nullsafe object operator'); + + }//end testNullsafeObjectOperator() + + + /** + * Data provider. + * + * @see testNullsafeObjectOperator() + * + * @return array + */ + public function dataNullsafeObjectOperator() + { + return [ + ['/* testNullsafeObjectOperator */'], + ['/* testNullsafeObjectOperatorWriteContext */'], + ]; + + }//end dataNullsafeObjectOperator() + + + /** + * Test that a question mark not followed by an object operator is tokenized as T_TERNARY_THEN. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * @param bool $testObjectOperator Whether to test for the next non-empty token being tokenized + * as an object operator. + * + * @dataProvider dataTernaryThen + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testTernaryThen($testMarker, $testObjectOperator=false) + { + $tokens = self::$phpcsFile->getTokens(); + + $operator = $this->getTargetToken($testMarker, $this->find); + $this->assertSame(T_INLINE_THEN, $tokens[$operator]['code'], 'Failed asserting code is inline then'); + $this->assertSame('T_INLINE_THEN', $tokens[$operator]['type'], 'Failed asserting type is inline then'); + + if ($testObjectOperator === true) { + $next = self::$phpcsFile->findNext(Tokens::$emptyTokens, ($operator + 1), null, true); + $this->assertSame(T_OBJECT_OPERATOR, $tokens[$next]['code'], 'Failed asserting code is object operator'); + $this->assertSame('T_OBJECT_OPERATOR', $tokens[$next]['type'], 'Failed asserting type is object operator'); + } + + }//end testTernaryThen() + + + /** + * Data provider. + * + * @see testTernaryThen() + * + * @return array + */ + public function dataTernaryThen() + { + return [ + ['/* testTernaryThen */'], + [ + '/* testParseErrorWhitespaceNotAllowed */', + true, + ], + [ + '/* testParseErrorCommentNotAllowed */', + true, + ], + ['/* testLiveCoding */'], + ]; + + }//end dataTernaryThen() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.inc new file mode 100644 index 0000000..38e5a47 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.inc @@ -0,0 +1,19 @@ + new namespace\Baz; diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.php new file mode 100644 index 0000000..1431795 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ScopeSettingWithNamespaceOperatorTest.php @@ -0,0 +1,98 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class ScopeSettingWithNamespaceOperatorTest extends AbstractMethodUnitTest +{ + + + /** + * Test that the scope opener/closers are set correctly when the namespace keyword is encountered as an operator. + * + * @param string $testMarker The comment which prefaces the target tokens in the test file. + * @param int|string[] $tokenTypes The token type to search for. + * @param int|string[] $open Optional. The token type for the scope opener. + * @param int|string[] $close Optional. The token type for the scope closer. + * + * @dataProvider dataScopeSetting + * @covers PHP_CodeSniffer\Tokenizers\Tokenizer::recurseScopeMap + * + * @return void + */ + public function testScopeSetting($testMarker, $tokenTypes, $open=T_OPEN_CURLY_BRACKET, $close=T_CLOSE_CURLY_BRACKET) + { + $tokens = self::$phpcsFile->getTokens(); + + $target = $this->getTargetToken($testMarker, $tokenTypes); + $opener = $this->getTargetToken($testMarker, $open); + $closer = $this->getTargetToken($testMarker, $close); + + $this->assertArrayHasKey('scope_opener', $tokens[$target], 'Scope opener missing'); + $this->assertArrayHasKey('scope_closer', $tokens[$target], 'Scope closer missing'); + $this->assertSame($opener, $tokens[$target]['scope_opener'], 'Scope opener not same'); + $this->assertSame($closer, $tokens[$target]['scope_closer'], 'Scope closer not same'); + + $this->assertArrayHasKey('scope_opener', $tokens[$opener], 'Scope opener missing for open curly'); + $this->assertArrayHasKey('scope_closer', $tokens[$opener], 'Scope closer missing for open curly'); + $this->assertSame($opener, $tokens[$opener]['scope_opener'], 'Scope opener not same for open curly'); + $this->assertSame($closer, $tokens[$opener]['scope_closer'], 'Scope closer not same for open curly'); + + $this->assertArrayHasKey('scope_opener', $tokens[$closer], 'Scope opener missing for close curly'); + $this->assertArrayHasKey('scope_closer', $tokens[$closer], 'Scope closer missing for close curly'); + $this->assertSame($opener, $tokens[$closer]['scope_opener'], 'Scope opener not same for close curly'); + $this->assertSame($closer, $tokens[$closer]['scope_closer'], 'Scope closer not same for close curly'); + + }//end testScopeSetting() + + + /** + * Data provider. + * + * @see testScopeSetting() + * + * @return array + */ + public function dataScopeSetting() + { + return [ + [ + '/* testClassExtends */', + [T_CLASS], + ], + [ + '/* testClassImplements */', + [T_ANON_CLASS], + ], + [ + '/* testInterfaceExtends */', + [T_INTERFACE], + ], + [ + '/* testFunctionReturnType */', + [T_FUNCTION], + ], + [ + '/* testClosureReturnType */', + [T_CLOSURE], + ], + [ + '/* testArrowFunctionReturnType */', + [T_FN], + [T_FN_ARROW], + [T_SEMICOLON], + ], + ]; + + }//end dataScopeSetting() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.inc new file mode 100644 index 0000000..60b23a5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.inc @@ -0,0 +1,111 @@ +function_call()[$x]; + +/* testStaticMethodCallDereferencing */ +$var = ClassName::function_call()[$x]; + +/* testPropertyDereferencing */ +$var = $obj->property[2]; + +/* testPropertyDereferencingWithInaccessibleName */ +$var = $ref->{'ref-type'}[1]; + +/* testStaticPropertyDereferencing */ +$var ClassName::$property[2]; + +/* testStringDereferencing */ +$var = 'PHP'[1]; + +/* testStringDereferencingDoubleQuoted */ +$var = "PHP"[$y]; + +/* testConstantDereferencing */ +$var = MY_CONSTANT[1]; + +/* testClassConstantDereferencing */ +$var ClassName::CONSTANT_NAME[2]; + +/* testMagicConstantDereferencing */ +$var = __FILE__[0]; + +/* testArrayAccessCurlyBraces */ +$var = $array{'key'}['key']; + +/* testArrayLiteralDereferencing */ +echo array(1, 2, 3)[0]; + +echo [1, 2, 3]/* testShortArrayLiteralDereferencing */[0]; + +/* testClassMemberDereferencingOnInstantiation1 */ +(new foo)[0]; + +/* testClassMemberDereferencingOnInstantiation2 */ +$a = (new Foo( array(1, array(4, 5), 3) ))[1][0]; + +/* testClassMemberDereferencingOnClone */ +echo (clone $iterable)[20]; + +/* testNullsafeMethodCallDereferencing */ +$var = $obj?->function_call()[$x]; + +/* testInterpolatedStringDereferencing */ +$var = "PHP{$rocks}"[1]; + +/* + * Short array brackets. + */ + +/* testShortArrayDeclarationEmpty */ +$array = []; + +/* testShortArrayDeclarationWithOneValue */ +$array = [1]; + +/* testShortArrayDeclarationWithMultipleValues */ +$array = [1, 2, 3]; + +/* testShortArrayDeclarationWithDereferencing */ +echo [1, 2, 3][0]; + +/* testShortListDeclaration */ +[ $a, $b ] = $array; + +[ $a, $b, /* testNestedListDeclaration */, [$c, $d]] = $array; + +/* testArrayWithinFunctionCall */ +$var = functionCall([$x, $y]); + +if ( true ) { + /* testShortListDeclarationAfterBracedControlStructure */ + [ $a ] = [ 'hi' ]; +} + +if ( true ) + /* testShortListDeclarationAfterNonBracedControlStructure */ + [ $a ] = [ 'hi' ]; + +if ( true ) : + /* testShortListDeclarationAfterAlternativeControlStructure */ + [ $a ] = [ 'hi' ]; +endif; + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +$array = [ diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.php new file mode 100644 index 0000000..3cf9cd1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/ShortArrayTest.php @@ -0,0 +1,135 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class ShortArrayTest extends AbstractMethodUnitTest +{ + + + /** + * Test that real square brackets are still tokenized as square brackets. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataSquareBrackets + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testSquareBrackets($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_OPEN_SQUARE_BRACKET, T_OPEN_SHORT_ARRAY]); + $this->assertSame(T_OPEN_SQUARE_BRACKET, $tokens[$opener]['code']); + $this->assertSame('T_OPEN_SQUARE_BRACKET', $tokens[$opener]['type']); + + if (isset($tokens[$opener]['bracket_closer']) === true) { + $closer = $tokens[$opener]['bracket_closer']; + $this->assertSame(T_CLOSE_SQUARE_BRACKET, $tokens[$closer]['code']); + $this->assertSame('T_CLOSE_SQUARE_BRACKET', $tokens[$closer]['type']); + } + + }//end testSquareBrackets() + + + /** + * Data provider. + * + * @see testSquareBrackets() + * + * @return array + */ + public function dataSquareBrackets() + { + return [ + 'array access 1' => ['/* testArrayAccess1 */'], + 'array access 2' => ['/* testArrayAccess2 */'], + 'array assignment' => ['/* testArrayAssignment */'], + 'function call dereferencing' => ['/* testFunctionCallDereferencing */'], + 'method call dereferencing' => ['/* testMethodCallDereferencing */'], + 'static method call dereferencing' => ['/* testStaticMethodCallDereferencing */'], + 'property dereferencing' => ['/* testPropertyDereferencing */'], + 'property dereferencing with inaccessable name' => ['/* testPropertyDereferencingWithInaccessibleName */'], + 'static property dereferencing' => ['/* testStaticPropertyDereferencing */'], + 'string dereferencing single quotes' => ['/* testStringDereferencing */'], + 'string dereferencing double quotes' => ['/* testStringDereferencingDoubleQuoted */'], + 'global constant dereferencing' => ['/* testConstantDereferencing */'], + 'class constant dereferencing' => ['/* testClassConstantDereferencing */'], + 'magic constant dereferencing' => ['/* testMagicConstantDereferencing */'], + 'array access with curly braces' => ['/* testArrayAccessCurlyBraces */'], + 'array literal dereferencing' => ['/* testArrayLiteralDereferencing */'], + 'short array literal dereferencing' => ['/* testShortArrayLiteralDereferencing */'], + 'class member dereferencing on instantiation 1' => ['/* testClassMemberDereferencingOnInstantiation1 */'], + 'class member dereferencing on instantiation 2' => ['/* testClassMemberDereferencingOnInstantiation2 */'], + 'class member dereferencing on clone' => ['/* testClassMemberDereferencingOnClone */'], + 'nullsafe method call dereferencing' => ['/* testNullsafeMethodCallDereferencing */'], + 'interpolated string dereferencing' => ['/* testInterpolatedStringDereferencing */'], + 'live coding' => ['/* testLiveCoding */'], + ]; + + }//end dataSquareBrackets() + + + /** + * Test that short arrays and short lists are still tokenized as short arrays. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataShortArrays + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testShortArrays($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_OPEN_SQUARE_BRACKET, T_OPEN_SHORT_ARRAY]); + $this->assertSame(T_OPEN_SHORT_ARRAY, $tokens[$opener]['code']); + $this->assertSame('T_OPEN_SHORT_ARRAY', $tokens[$opener]['type']); + + if (isset($tokens[$opener]['bracket_closer']) === true) { + $closer = $tokens[$opener]['bracket_closer']; + $this->assertSame(T_CLOSE_SHORT_ARRAY, $tokens[$closer]['code']); + $this->assertSame('T_CLOSE_SHORT_ARRAY', $tokens[$closer]['type']); + } + + }//end testShortArrays() + + + /** + * Data provider. + * + * @see testShortArrays() + * + * @return array + */ + public function dataShortArrays() + { + return [ + 'short array empty' => ['/* testShortArrayDeclarationEmpty */'], + 'short array with value' => ['/* testShortArrayDeclarationWithOneValue */'], + 'short array with values' => ['/* testShortArrayDeclarationWithMultipleValues */'], + 'short array with dereferencing' => ['/* testShortArrayDeclarationWithDereferencing */'], + 'short list' => ['/* testShortListDeclaration */'], + 'short list nested' => ['/* testNestedListDeclaration */'], + 'short array within function call' => ['/* testArrayWithinFunctionCall */'], + 'short list after braced control structure' => ['/* testShortListDeclarationAfterBracedControlStructure */'], + 'short list after non-braced control structure' => ['/* testShortListDeclarationAfterNonBracedControlStructure */'], + 'short list after alternative control structure' => ['/* testShortListDeclarationAfterAlternativeControlStructure */'], + ]; + + }//end dataShortArrays() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceTest.inc new file mode 100644 index 0000000..3bf013c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceTest.inc @@ -0,0 +1,139 @@ + + + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class StableCommentWhitespaceTest extends AbstractMethodUnitTest +{ + + + /** + * Test that comment tokenization with new lines at the end of the comment is stable. + * + * @param string $testMarker The comment prefacing the test. + * @param array $expectedTokens The tokenization expected. + * + * @dataProvider dataCommentTokenization + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testCommentTokenization($testMarker, $expectedTokens) + { + $tokens = self::$phpcsFile->getTokens(); + $comment = $this->getTargetToken($testMarker, Tokens::$commentTokens); + + foreach ($expectedTokens as $key => $tokenInfo) { + $this->assertSame(constant($tokenInfo['type']), $tokens[$comment]['code']); + $this->assertSame($tokenInfo['type'], $tokens[$comment]['type']); + $this->assertSame($tokenInfo['content'], $tokens[$comment]['content']); + + ++$comment; + } + + }//end testCommentTokenization() + + + /** + * Data provider. + * + * @see testCommentTokenization() + * + * @return array + */ + public function dataCommentTokenization() + { + return [ + [ + '/* testSingleLineSlashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashCommentTrailing */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashAnnotation */', + [ + [ + 'type' => 'T_PHPCS_DISABLE', + 'content' => '// phpcs:disable Stnd.Cat +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithIndent */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationStart */', + [ + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationMiddle */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// @phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineStarComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Single line star comment */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineStarCommentTrailing */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineStarAnnotation */', + [ + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '/* phpcs:ignore Stnd.Cat */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineStarComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment3 */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineStarCommentWithIndent */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment3 */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineStarCommentWithAnnotationStart */', + [ + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '/* @phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment3 */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineStarCommentWithAnnotationMiddle */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment1 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => ' * phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment3 */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineStarCommentWithAnnotationEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => ' * Comment2 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => ' * phpcs:ignore Stnd.Cat */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + + [ + '/* testSingleLineDocblockComment */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineDocblockCommentTrailing */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineDocblockAnnotation */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => 'phpcs:ignore Stnd.Cat.Sniff ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + + [ + '/* testMultiLineDocblockComment */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment1', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment2', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_TAG', + 'content' => '@tag', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineDocblockCommentWithIndent */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment1', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment2', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_TAG', + 'content' => '@tag', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineDocblockCommentWithAnnotation */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => 'phpcs:ignore Stnd.Cat', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_TAG', + 'content' => '@tag', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineDocblockCommentWithTagAnnotation */', + [ + [ + 'type' => 'T_DOC_COMMENT_OPEN_TAG', + 'content' => '/**', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '@phpcs:ignore Stnd.Cat', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STAR', + 'content' => '*', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_TAG', + 'content' => '@tag', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_STRING', + 'content' => 'Comment', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_DOC_COMMENT_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_DOC_COMMENT_CLOSE_TAG', + 'content' => '*/', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineHashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineHashCommentTrailing */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineHashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineHashCommentWithIndent */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment1 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment2 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashCommentNoNewLineAtEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Slash ', + ], + [ + 'type' => 'T_CLOSE_TAG', + 'content' => '?> +', + ], + ], + ], + [ + '/* testSingleLineHashCommentNoNewLineAtEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Hash ', + ], + [ + 'type' => 'T_CLOSE_TAG', + 'content' => '?> +', + ], + ], + ], + [ + '/* testCommentAtEndOfFile */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment', + ], + ], + ], + ]; + + }//end dataCommentTokenization() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceWinTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceWinTest.inc new file mode 100644 index 0000000..6ca7026 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/StableCommentWhitespaceWinTest.inc @@ -0,0 +1,63 @@ + + + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; +use PHP_CodeSniffer\Util\Tokens; + +class StableCommentWhitespaceWinTest extends AbstractMethodUnitTest +{ + + + /** + * Test that comment tokenization with new lines at the end of the comment is stable. + * + * @param string $testMarker The comment prefacing the test. + * @param array $expectedTokens The tokenization expected. + * + * @dataProvider dataCommentTokenization + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testCommentTokenization($testMarker, $expectedTokens) + { + $tokens = self::$phpcsFile->getTokens(); + $comment = $this->getTargetToken($testMarker, Tokens::$commentTokens); + + foreach ($expectedTokens as $key => $tokenInfo) { + $this->assertSame(constant($tokenInfo['type']), $tokens[$comment]['code']); + $this->assertSame($tokenInfo['type'], $tokens[$comment]['type']); + $this->assertSame($tokenInfo['content'], $tokens[$comment]['content']); + + ++$comment; + } + + }//end testCommentTokenization() + + + /** + * Data provider. + * + * @see testCommentTokenization() + * + * @return array + */ + public function dataCommentTokenization() + { + return [ + [ + '/* testSingleLineSlashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashCommentTrailing */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashAnnotation */', + [ + [ + 'type' => 'T_PHPCS_DISABLE', + 'content' => '// phpcs:disable Stnd.Cat +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithIndent */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationStart */', + [ + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationMiddle */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// @phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineSlashCommentWithAnnotationEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '// Comment2 +', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// phpcs:ignore Stnd.Cat +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineSlashCommentNoNewLineAtEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '// Slash ', + ], + [ + 'type' => 'T_CLOSE_TAG', + 'content' => '?> +', + ], + ], + ], + [ + '/* testSingleLineHashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineHashCommentTrailing */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineHashComment */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment1 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment2 +', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testMultiLineHashCommentWithIndent */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment1 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment2 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '# Comment3 +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testSingleLineHashCommentNoNewLineAtEnd */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '# Hash ', + ], + [ + 'type' => 'T_CLOSE_TAG', + 'content' => '?> +', + ], + ], + ], + [ + '/* testCommentAtEndOfFile */', + [ + [ + 'type' => 'T_COMMENT', + 'content' => '/* Comment', + ], + ], + ], + ]; + + }//end dataCommentTokenization() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.inc new file mode 100644 index 0000000..ad421cb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.inc @@ -0,0 +1,123 @@ + $param & $int; + +/* testTypeIntersectionArrowReturnType */ +$arrowWithReturnType = fn ($param) : Foo&Bar => $param * 10; + +/* testBitwiseAndInArrayKey */ +$array = array( + A & B => /* testBitwiseAndInArrayValue */ B & C +); + +/* testBitwiseAndInShortArrayKey */ +$array = [ + A & B => /* testBitwiseAndInShortArrayValue */ B & C +]; + +/* testBitwiseAndNonArrowFnFunctionCall */ +$obj->fn($something & $else); + +/* testBitwiseAnd6 */ +function &fn(/* testTypeIntersectionNonArrowFunctionDeclaration */ Foo&Bar $something) {} + +/* testTypeIntersectionWithInvalidTypes */ +function (int&string $var) {}; + +/* testLiveCoding */ +// Intentional parse error. This has to be the last test in the file. +return function( Foo& diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.php new file mode 100644 index 0000000..fcfd191 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/TypeIntersectionTest.php @@ -0,0 +1,139 @@ + + * @author Jaroslav Hanslík + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class TypeIntersectionTest extends AbstractMethodUnitTest +{ + + + /** + * Test that non-intersection type bitwise and tokens are still tokenized as bitwise and. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataBitwiseAnd + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testBitwiseAnd($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_BITWISE_AND, T_TYPE_INTERSECTION]); + $this->assertSame(T_BITWISE_AND, $tokens[$opener]['code']); + $this->assertSame('T_BITWISE_AND', $tokens[$opener]['type']); + + }//end testBitwiseAnd() + + + /** + * Data provider. + * + * @see testBitwiseAnd() + * + * @return array + */ + public function dataBitwiseAnd() + { + return [ + ['/* testBitwiseAnd1 */'], + ['/* testBitwiseAnd2 */'], + ['/* testBitwiseAndPropertyDefaultValue */'], + ['/* testBitwiseAndParamDefaultValue */'], + ['/* testBitwiseAnd3 */'], + ['/* testBitwiseAnd4 */'], + ['/* testBitwiseAnd5 */'], + ['/* testBitwiseAndClosureParamDefault */'], + ['/* testBitwiseAndArrowParamDefault */'], + ['/* testBitwiseAndArrowExpression */'], + ['/* testBitwiseAndInArrayKey */'], + ['/* testBitwiseAndInArrayValue */'], + ['/* testBitwiseAndInShortArrayKey */'], + ['/* testBitwiseAndInShortArrayValue */'], + ['/* testBitwiseAndNonArrowFnFunctionCall */'], + ['/* testBitwiseAnd6 */'], + ['/* testLiveCoding */'], + ]; + + }//end dataBitwiseAnd() + + + /** + * Test that bitwise and tokens when used as part of a intersection type are tokenized as `T_TYPE_INTERSECTION`. + * + * @param string $testMarker The comment which prefaces the target token in the test file. + * + * @dataProvider dataTypeIntersection + * @covers PHP_CodeSniffer\Tokenizers\PHP::processAdditional + * + * @return void + */ + public function testTypeIntersection($testMarker) + { + $tokens = self::$phpcsFile->getTokens(); + + $opener = $this->getTargetToken($testMarker, [T_BITWISE_AND, T_TYPE_INTERSECTION]); + $this->assertSame(T_TYPE_INTERSECTION, $tokens[$opener]['code']); + $this->assertSame('T_TYPE_INTERSECTION', $tokens[$opener]['type']); + + }//end testTypeIntersection() + + + /** + * Data provider. + * + * @see testTypeIntersection() + * + * @return array + */ + public function dataTypeIntersection() + { + return [ + ['/* testTypeIntersectionPropertySimple */'], + ['/* testTypeIntersectionPropertyReverseModifierOrder */'], + ['/* testTypeIntersectionPropertyMulti1 */'], + ['/* testTypeIntersectionPropertyMulti2 */'], + ['/* testTypeIntersectionPropertyMulti3 */'], + ['/* testTypeIntersectionPropertyNamespaceRelative */'], + ['/* testTypeIntersectionPropertyPartiallyQualified */'], + ['/* testTypeIntersectionPropertyFullyQualified */'], + ['/* testTypeIntersectionPropertyWithReadOnlyKeyword */'], + ['/* testTypeIntersectionPropertyWithStaticKeyword */'], + ['/* testTypeIntersectionParam1 */'], + ['/* testTypeIntersectionParam2 */'], + ['/* testTypeIntersectionParam3 */'], + ['/* testTypeIntersectionParamNamespaceRelative */'], + ['/* testTypeIntersectionParamPartiallyQualified */'], + ['/* testTypeIntersectionParamFullyQualified */'], + ['/* testTypeIntersectionReturnType */'], + ['/* testTypeIntersectionConstructorPropertyPromotion */'], + ['/* testTypeIntersectionAbstractMethodReturnType1 */'], + ['/* testTypeIntersectionAbstractMethodReturnType2 */'], + ['/* testTypeIntersectionReturnTypeNamespaceRelative */'], + ['/* testTypeIntersectionReturnPartiallyQualified */'], + ['/* testTypeIntersectionReturnFullyQualified */'], + ['/* testTypeIntersectionClosureParamIllegalNullable */'], + ['/* testTypeIntersectionWithReference */'], + ['/* testTypeIntersectionWithSpreadOperator */'], + ['/* testTypeIntersectionClosureReturn */'], + ['/* testTypeIntersectionArrowParam */'], + ['/* testTypeIntersectionArrowReturnType */'], + ['/* testTypeIntersectionNonArrowFunctionDeclaration */'], + ['/* testTypeIntersectionWithInvalidTypes */'], + ]; + + }//end dataTypeIntersection() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/UndoNamespacedNameSingleTokenTest.inc b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/UndoNamespacedNameSingleTokenTest.inc new file mode 100644 index 0000000..540f72c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Tokenizer/UndoNamespacedNameSingleTokenTest.inc @@ -0,0 +1,147 @@ + + * @copyright 2020 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Tokenizer; + +use PHP_CodeSniffer\Tests\Core\AbstractMethodUnitTest; + +class UndoNamespacedNameSingleTokenTest extends AbstractMethodUnitTest +{ + + + /** + * Test that identifier names are tokenized the same across PHP versions, based on the PHP 5/7 tokenization. + * + * @param string $testMarker The comment prefacing the test. + * @param array $expectedTokens The tokenization expected. + * + * @dataProvider dataIdentifierTokenization + * @covers PHP_CodeSniffer\Tokenizers\PHP::tokenize + * + * @return void + */ + public function testIdentifierTokenization($testMarker, $expectedTokens) + { + $tokens = self::$phpcsFile->getTokens(); + $identifier = $this->getTargetToken($testMarker, constant($expectedTokens[0]['type'])); + + foreach ($expectedTokens as $key => $tokenInfo) { + $this->assertSame(constant($tokenInfo['type']), $tokens[$identifier]['code']); + $this->assertSame($tokenInfo['type'], $tokens[$identifier]['type']); + $this->assertSame($tokenInfo['content'], $tokens[$identifier]['content']); + + ++$identifier; + } + + }//end testIdentifierTokenization() + + + /** + * Data provider. + * + * @see testIdentifierTokenization() + * + * @return array + */ + public function dataIdentifierTokenization() + { + return [ + [ + '/* testNamespaceDeclaration */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Package', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testNamespaceDeclarationWithLevels */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'SubLevel', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Domain', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testUseStatement */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testUseStatementWithLevels */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Domain', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testFunctionUseStatement */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'function', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testFunctionUseStatementWithLevels */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'function', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_in_ns', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testConstantUseStatement */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'const', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'CONSTANT_NAME', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testConstantUseStatementWithLevels */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'const', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'OTHER_CONSTANT', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testMultiUseUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'UnqualifiedClassName', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + ], + ], + [ + '/* testMultiUsePartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Sublevel', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'PartiallyClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testGroupUseStatement */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_OPEN_USE_GROUP', + 'content' => '{', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'AnotherDomain', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_grouped', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'const', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'CONSTANT_GROUPED', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Sub', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'YetAnotherDomain', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'SubLevelA', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_grouped_too', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'const', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'SubLevelB', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'CONSTANT_GROUPED_TOO', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_CLOSE_USE_GROUP', + 'content' => '}', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testClassName */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'MyClass', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testExtendedFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'FQN', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testImplementsRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + ], + ], + [ + '/* testImplementsFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Fully', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Qualified', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + ], + ], + [ + '/* testImplementsUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Unqualified', + ], + [ + 'type' => 'T_COMMA', + 'content' => ',', + ], + ], + ], + [ + '/* testImplementsPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Sub', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + [ + '/* testFunctionName */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testTypeDeclarationRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_TYPE_UNION', + 'content' => '|', + ], + [ + 'type' => 'T_STRING', + 'content' => 'object', + ], + ], + ], + [ + '/* testTypeDeclarationFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Fully', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Qualified', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testTypeDeclarationUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Unqualified', + ], + [ + 'type' => 'T_TYPE_UNION', + 'content' => '|', + ], + [ + 'type' => 'T_FALSE', + 'content' => 'false', + ], + ], + ], + [ + '/* testTypeDeclarationPartiallyQualified */', + [ + [ + 'type' => 'T_NULLABLE', + 'content' => '?', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Sublevel', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testReturnTypeFQN */', + [ + [ + 'type' => 'T_NULLABLE', + 'content' => '?', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testFunctionCallRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'NameSpace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testFunctionCallFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Package', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testFunctionCallUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testFunctionPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testCatchRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'SubLevel', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Exception', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testCatchFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Exception', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testCatchUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Exception', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testCatchPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Exception', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testNewRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testNewFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Vendor', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testNewUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testNewPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testDoubleColonRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_DOUBLE_COLON', + 'content' => '::', + ], + ], + ], + [ + '/* testDoubleColonFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_DOUBLE_COLON', + 'content' => '::', + ], + ], + ], + [ + '/* testDoubleColonUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_DOUBLE_COLON', + 'content' => '::', + ], + ], + ], + [ + '/* testDoubleColonPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Level', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_DOUBLE_COLON', + 'content' => '::', + ], + ], + ], + [ + '/* testInstanceOfRelative */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testInstanceOfFQN */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Full', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_CLOSE_PARENTHESIS', + 'content' => ')', + ], + ], + ], + [ + '/* testInstanceOfUnqualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + ], + ], + [ + '/* testInstanceOfPartiallyQualified */', + [ + [ + 'type' => 'T_STRING', + 'content' => 'Partially', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'ClassName', + ], + [ + 'type' => 'T_SEMICOLON', + 'content' => ';', + ], + ], + ], + [ + '/* testInvalidInPHP8Whitespace */', + [ + [ + 'type' => 'T_NAMESPACE', + 'content' => 'namespace', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Sublevel', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_STRING', + 'content' => 'function_name', + ], + [ + 'type' => 'T_OPEN_PARENTHESIS', + 'content' => '(', + ], + ], + ], + [ + '/* testInvalidInPHP8Comments */', + [ + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Fully', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_PHPCS_IGNORE', + 'content' => '// phpcs:ignore Stnd.Cat.Sniff -- for reasons +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Qualified', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_COMMENT', + 'content' => '/* comment */', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' ', + ], + [ + 'type' => 'T_NS_SEPARATOR', + 'content' => '\\', + ], + [ + 'type' => 'T_STRING', + 'content' => 'Name', + ], + [ + 'type' => 'T_WHITESPACE', + 'content' => ' +', + ], + ], + ], + ]; + + }//end dataIdentifierTokenization() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Util/IsCamelCapsTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Util/IsCamelCapsTest.php new file mode 100644 index 0000000..2a1729b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Util/IsCamelCapsTest.php @@ -0,0 +1,140 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Util; + +use PHP_CodeSniffer\Util\Common; +use PHPUnit\Framework\TestCase; + +/** + * Tests for the \PHP_CodeSniffer\Util\Common::isCamelCaps method. + * + * @covers \PHP_CodeSniffer\Util\Common::isCamelCaps + */ +class IsCamelCapsTest extends TestCase +{ + + + /** + * Test valid public function/method names. + * + * @return void + */ + public function testValidNotClassFormatPublic() + { + $this->assertTrue(Common::isCamelCaps('thisIsCamelCaps', false, true, true)); + $this->assertTrue(Common::isCamelCaps('thisISCamelCaps', false, true, false)); + + }//end testValidNotClassFormatPublic() + + + /** + * Test invalid public function/method names. + * + * @return void + */ + public function testInvalidNotClassFormatPublic() + { + $this->assertFalse(Common::isCamelCaps('_thisIsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('thisISCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('ThisIsCamelCaps', false, true, true)); + + $this->assertFalse(Common::isCamelCaps('3thisIsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('*thisIsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('-thisIsCamelCaps', false, true, true)); + + $this->assertFalse(Common::isCamelCaps('this*IsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('this-IsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('this_IsCamelCaps', false, true, true)); + $this->assertFalse(Common::isCamelCaps('this_is_camel_caps', false, true, true)); + + }//end testInvalidNotClassFormatPublic() + + + /** + * Test valid private method names. + * + * @return void + */ + public function testValidNotClassFormatPrivate() + { + $this->assertTrue(Common::isCamelCaps('_thisIsCamelCaps', false, false, true)); + $this->assertTrue(Common::isCamelCaps('_thisISCamelCaps', false, false, false)); + $this->assertTrue(Common::isCamelCaps('_i18N', false, false, true)); + $this->assertTrue(Common::isCamelCaps('_i18n', false, false, true)); + + }//end testValidNotClassFormatPrivate() + + + /** + * Test invalid private method names. + * + * @return void + */ + public function testInvalidNotClassFormatPrivate() + { + $this->assertFalse(Common::isCamelCaps('thisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('_thisISCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('__thisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('__thisISCamelCaps', false, false, false)); + + $this->assertFalse(Common::isCamelCaps('3thisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('*thisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('-thisIsCamelCaps', false, false, true)); + $this->assertFalse(Common::isCamelCaps('_this_is_camel_caps', false, false, true)); + + }//end testInvalidNotClassFormatPrivate() + + + /** + * Test valid class names. + * + * @return void + */ + public function testValidClassFormatPublic() + { + $this->assertTrue(Common::isCamelCaps('ThisIsCamelCaps', true, true, true)); + $this->assertTrue(Common::isCamelCaps('ThisISCamelCaps', true, true, false)); + $this->assertTrue(Common::isCamelCaps('This3IsCamelCaps', true, true, false)); + + }//end testValidClassFormatPublic() + + + /** + * Test invalid class names. + * + * @return void + */ + public function testInvalidClassFormat() + { + $this->assertFalse(Common::isCamelCaps('thisIsCamelCaps', true)); + $this->assertFalse(Common::isCamelCaps('This-IsCamelCaps', true)); + $this->assertFalse(Common::isCamelCaps('This_Is_Camel_Caps', true)); + + }//end testInvalidClassFormat() + + + /** + * Test invalid class names with the private flag set. + * + * Note that the private flag is ignored if the class format + * flag is set, so these names are all invalid. + * + * @return void + */ + public function testInvalidClassFormatPrivate() + { + $this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', true, true)); + $this->assertFalse(Common::isCamelCaps('_ThisIsCamelCaps', true, false)); + + }//end testInvalidClassFormatPrivate() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Core/Util/SuggestTypeTest.php b/vendor/squizlabs/php_codesniffer/tests/Core/Util/SuggestTypeTest.php new file mode 100644 index 0000000..a5a862f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Core/Util/SuggestTypeTest.php @@ -0,0 +1,224 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Core\Util; + +use PHP_CodeSniffer\Util\Common; +use PHPUnit\Framework\TestCase; + +/** + * Tests for the \PHP_CodeSniffer\Util\Sniffs\Comments::suggestType() method. + * + * @covers \PHP_CodeSniffer\Util\Common::suggestType + */ +class SuggestTypeTest extends TestCase +{ + + + /** + * Test passing an empty type to the suggestType() method. + * + * @return void + */ + public function testSuggestTypeEmpty() + { + $this->assertSame('', Common::suggestType('')); + + }//end testSuggestTypeEmpty() + + + /** + * Test passing one of the allowed types to the suggestType() method. + * + * @param string $varType The type. + * + * @dataProvider dataSuggestTypeAllowedType + * + * @return void + */ + public function testSuggestTypeAllowedType($varType) + { + $result = Common::suggestType($varType); + $this->assertSame($varType, $result); + + }//end testSuggestTypeAllowedType() + + + /** + * Data provider. + * + * @see testSuggestTypeAllowedType() + * + * @return array> + */ + public function dataSuggestTypeAllowedType() + { + $data = []; + foreach (Common::$allowedTypes as $type) { + $data['Type: '.$type] = [$type]; + } + + return $data; + + }//end dataSuggestTypeAllowedType() + + + /** + * Test passing one of the allowed types in the wrong case to the suggestType() method. + * + * @param string $varType The type found. + * @param string $expected Expected suggested type. + * + * @dataProvider dataSuggestTypeAllowedTypeWrongCase + * + * @return void + */ + public function testSuggestTypeAllowedTypeWrongCase($varType, $expected) + { + $result = Common::suggestType($varType); + $this->assertSame($expected, $result); + + }//end testSuggestTypeAllowedTypeWrongCase() + + + /** + * Data provider. + * + * @see testSuggestTypeAllowedTypeWrongCase() + * + * @return array> + */ + public function dataSuggestTypeAllowedTypeWrongCase() + { + $data = []; + foreach (Common::$allowedTypes as $type) { + $data['Mixed case: '.$type] = [ + 'varType' => ucfirst($type), + 'expected' => $type, + ]; + $data['Uppercase: '.$type] = [ + 'varType' => strtoupper($type), + 'expected' => $type, + ]; + } + + return $data; + + }//end dataSuggestTypeAllowedTypeWrongCase() + + + /** + * Test the suggestType() method for all other cases. + * + * @param string $varType The type found. + * @param string $expected Expected suggested type. + * + * @dataProvider dataSuggestTypeOther + * + * @return void + */ + public function testSuggestTypeOther($varType, $expected) + { + $result = Common::suggestType($varType); + $this->assertSame($expected, $result); + + }//end testSuggestTypeOther() + + + /** + * Data provider. + * + * @see testSuggestTypeOther() + * + * @return array> + */ + public function dataSuggestTypeOther() + { + return [ + // Short forms. + 'Short form type: bool, lowercase' => [ + 'varType' => 'bool', + 'expected' => 'boolean', + ], + 'Short form type: bool, uppercase' => [ + 'varType' => 'BOOL', + 'expected' => 'boolean', + ], + 'Short form type: double, lowercase' => [ + 'varType' => 'double', + 'expected' => 'float', + ], + 'Short form type: real, mixed case' => [ + 'varType' => 'Real', + 'expected' => 'float', + ], + 'Short form type: double, mixed case' => [ + 'varType' => 'DoUbLe', + 'expected' => 'float', + ], + 'Short form type: int, lowercase' => [ + 'varType' => 'int', + 'expected' => 'integer', + ], + 'Short form type: int, uppercase' => [ + 'varType' => 'INT', + 'expected' => 'integer', + ], + + // Array types. + 'Array type: mixed case keyword, empty parentheses' => [ + 'varType' => 'Array()', + 'expected' => 'array', + ], + 'Array type: short form type as value within the parentheses' => [ + 'varType' => 'array(real)', + 'expected' => 'array(float)', + ], + 'Array type: short form type as key within the parentheses' => [ + 'varType' => 'array(int => object)', + 'expected' => 'array(integer => object)', + ], + 'Array type: valid specification' => [ + 'varType' => 'array(integer => array(string => resource))', + 'expected' => 'array(integer => array(string => resource))', + ], + 'Array type: short form + uppercase types within the parentheses' => [ + 'varType' => 'ARRAY(BOOL => DOUBLE)', + 'expected' => 'array(boolean => float)', + ], + 'Array type: no space around the arrow within the parentheses' => [ + 'varType' => 'array(string=>resource)', + 'expected' => 'array(string => resource)', + ], + + // Incomplete array type. + 'Array type: incomplete specification' => [ + 'varType' => 'array(int =>', + 'expected' => 'array', + ], + + // Custom types are returned unchanged. + 'Unknown type: " => "' => [ + 'varType' => ' => ', + 'expected' => ' => ', + ], + 'Unknown type: "string[]"' => [ + 'varType' => 'string[]', + 'expected' => 'string[]', + ], + 'Unknown type: "\DateTime"' => [ + 'varType' => '\DateTime', + 'expected' => '\DateTime', + ], + ]; + + }//end dataSuggestTypeOther() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/FileList.php b/vendor/squizlabs/php_codesniffer/tests/FileList.php new file mode 100644 index 0000000..1672411 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/FileList.php @@ -0,0 +1,94 @@ + + * @copyright 2019 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests; + +class FileList +{ + + /** + * The path to the project root directory. + * + * @var string + */ + protected $rootPath; + + /** + * Recursive directory iterator. + * + * @var \DirectoryIterator + */ + public $fileIterator; + + /** + * Base regex to use if no filter regex is provided. + * + * Matches based on: + * - File path starts with the project root (replacement done in constructor). + * - Don't match .git/ files. + * - Don't match dot files, i.e. "." or "..". + * - Don't match backup files. + * - Match everything else in a case-insensitive manner. + * + * @var string + */ + private $baseRegex = '`^%s(?!\.git/)(?!(.*/)?\.+$)(?!.*\.(bak|orig)).*$`Dix'; + + + /** + * Constructor. + * + * @param string $directory The directory to examine. + * @param string $rootPath Path to the project root. + * @param string $filter PCRE regular expression to filter the file list with. + */ + public function __construct($directory, $rootPath='', $filter='') + { + $this->rootPath = $rootPath; + + $directory = new \RecursiveDirectoryIterator( + $directory, + \RecursiveDirectoryIterator::UNIX_PATHS + ); + $flattened = new \RecursiveIteratorIterator( + $directory, + \RecursiveIteratorIterator::LEAVES_ONLY, + \RecursiveIteratorIterator::CATCH_GET_CHILD + ); + + if ($filter === '') { + $filter = sprintf($this->baseRegex, preg_quote($this->rootPath)); + } + + $this->fileIterator = new \RegexIterator($flattened, $filter); + + return $this; + + }//end __construct() + + + /** + * Retrieve the filtered file list as an array. + * + * @return array + */ + public function getList() + { + $fileList = []; + + foreach ($this->fileIterator as $file) { + $fileList[] = str_replace($this->rootPath, '', $file); + } + + return $fileList; + + }//end getList() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Standards/AbstractSniffUnitTest.php b/vendor/squizlabs/php_codesniffer/tests/Standards/AbstractSniffUnitTest.php new file mode 100644 index 0000000..9bf6158 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Standards/AbstractSniffUnitTest.php @@ -0,0 +1,462 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Standards; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Files\LocalFile; +use PHP_CodeSniffer\Util\Common; +use PHPUnit\Framework\TestCase; + +abstract class AbstractSniffUnitTest extends TestCase +{ + + /** + * Enable or disable the backup and restoration of the $GLOBALS array. + * Overwrite this attribute in a child class of TestCase. + * Setting this attribute in setUp() has no effect! + * + * @var boolean + */ + protected $backupGlobals = false; + + /** + * The path to the standard's main directory. + * + * @var string + */ + public $standardsDir = null; + + /** + * The path to the standard's test directory. + * + * @var string + */ + public $testsDir = null; + + + /** + * Sets up this unit test. + * + * @before + * + * @return void + */ + protected function setUpPrerequisites() + { + $class = get_class($this); + $this->standardsDir = $GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'][$class]; + $this->testsDir = $GLOBALS['PHP_CODESNIFFER_TEST_DIRS'][$class]; + + }//end setUpPrerequisites() + + + /** + * Get a list of all test files to check. + * + * These will have the same base as the sniff name but different extensions. + * We ignore the .php file as it is the class. + * + * @param string $testFileBase The base path that the unit tests files will have. + * + * @return string[] + */ + protected function getTestFiles($testFileBase) + { + $testFiles = []; + + $dir = substr($testFileBase, 0, strrpos($testFileBase, DIRECTORY_SEPARATOR)); + $di = new \DirectoryIterator($dir); + + foreach ($di as $file) { + $path = $file->getPathname(); + if (substr($path, 0, strlen($testFileBase)) === $testFileBase) { + if ($path !== $testFileBase.'php' && substr($path, -5) !== 'fixed' && substr($path, -4) !== '.bak') { + $testFiles[] = $path; + } + } + } + + // Put them in order. + sort($testFiles, SORT_NATURAL); + + return $testFiles; + + }//end getTestFiles() + + + /** + * Should this test be skipped for some reason. + * + * @return boolean + */ + protected function shouldSkipTest() + { + return false; + + }//end shouldSkipTest() + + + /** + * Tests the extending classes Sniff class. + * + * @return void + * @throws \PHPUnit\Framework\Exception + */ + final public function testSniff() + { + // Skip this test if we can't run in this environment. + if ($this->shouldSkipTest() === true) { + $this->markTestSkipped(); + } + + $sniffCode = Common::getSniffCode(get_class($this)); + list($standardName, $categoryName, $sniffName) = explode('.', $sniffCode); + + $testFileBase = $this->testsDir.$categoryName.DIRECTORY_SEPARATOR.$sniffName.'UnitTest.'; + + // Get a list of all test files to check. + $testFiles = $this->getTestFiles($testFileBase); + $GLOBALS['PHP_CODESNIFFER_SNIFF_CASE_FILES'][] = $testFiles; + + if (isset($GLOBALS['PHP_CODESNIFFER_CONFIG']) === true) { + $config = $GLOBALS['PHP_CODESNIFFER_CONFIG']; + } else { + $config = new Config(); + $config->cache = false; + $GLOBALS['PHP_CODESNIFFER_CONFIG'] = $config; + } + + $config->standards = [$standardName]; + $config->sniffs = [$sniffCode]; + $config->ignored = []; + + if (isset($GLOBALS['PHP_CODESNIFFER_RULESETS']) === false) { + $GLOBALS['PHP_CODESNIFFER_RULESETS'] = []; + } + + if (isset($GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName]) === false) { + $ruleset = new Ruleset($config); + $GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName] = $ruleset; + } + + $ruleset = $GLOBALS['PHP_CODESNIFFER_RULESETS'][$standardName]; + + $sniffFile = $this->standardsDir.DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$categoryName.DIRECTORY_SEPARATOR.$sniffName.'Sniff.php'; + + $sniffClassName = substr(get_class($this), 0, -8).'Sniff'; + $sniffClassName = str_replace('\Tests\\', '\Sniffs\\', $sniffClassName); + $sniffClassName = Common::cleanSniffClass($sniffClassName); + + $restrictions = [strtolower($sniffClassName) => true]; + $ruleset->registerSniffs([$sniffFile], $restrictions, []); + $ruleset->populateTokenListeners(); + + $failureMessages = []; + foreach ($testFiles as $testFile) { + $filename = basename($testFile); + $oldConfig = $config->getSettings(); + + try { + $this->setCliValues($filename, $config); + $phpcsFile = new LocalFile($testFile, $ruleset, $config); + $phpcsFile->process(); + } catch (RuntimeException $e) { + $this->fail('An unexpected exception has been caught: '.$e->getMessage()); + } + + $failures = $this->generateFailureMessages($phpcsFile); + $failureMessages = array_merge($failureMessages, $failures); + + if ($phpcsFile->getFixableCount() > 0) { + // Attempt to fix the errors. + $phpcsFile->fixer->fixFile(); + $fixable = $phpcsFile->getFixableCount(); + if ($fixable > 0) { + $failureMessages[] = "Failed to fix $fixable fixable violations in $filename"; + } + + // Check for a .fixed file to check for accuracy of fixes. + $fixedFile = $testFile.'.fixed'; + if (file_exists($fixedFile) === true) { + $diff = $phpcsFile->fixer->generateDiff($fixedFile); + if (trim($diff) !== '') { + $filename = basename($testFile); + $fixedFilename = basename($fixedFile); + $failureMessages[] = "Fixed version of $filename does not match expected version in $fixedFilename; the diff is\n$diff"; + } + } + } + + // Restore the config. + $config->setSettings($oldConfig); + }//end foreach + + if (empty($failureMessages) === false) { + $this->fail(implode(PHP_EOL, $failureMessages)); + } + + }//end testSniff() + + + /** + * Generate a list of test failures for a given sniffed file. + * + * @param \PHP_CodeSniffer\Files\LocalFile $file The file being tested. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException + */ + public function generateFailureMessages(LocalFile $file) + { + $testFile = $file->getFilename(); + + $foundErrors = $file->getErrors(); + $foundWarnings = $file->getWarnings(); + $expectedErrors = $this->getErrorList(basename($testFile)); + $expectedWarnings = $this->getWarningList(basename($testFile)); + + if (is_array($expectedErrors) === false) { + throw new RuntimeException('getErrorList() must return an array'); + } + + if (is_array($expectedWarnings) === false) { + throw new RuntimeException('getWarningList() must return an array'); + } + + /* + We merge errors and warnings together to make it easier + to iterate over them and produce the errors string. In this way, + we can report on errors and warnings in the same line even though + it's not really structured to allow that. + */ + + $allProblems = []; + $failureMessages = []; + + foreach ($foundErrors as $line => $lineErrors) { + foreach ($lineErrors as $column => $errors) { + if (isset($allProblems[$line]) === false) { + $allProblems[$line] = [ + 'expected_errors' => 0, + 'expected_warnings' => 0, + 'found_errors' => [], + 'found_warnings' => [], + ]; + } + + $foundErrorsTemp = []; + foreach ($allProblems[$line]['found_errors'] as $foundError) { + $foundErrorsTemp[] = $foundError; + } + + $errorsTemp = []; + foreach ($errors as $foundError) { + $errorsTemp[] = $foundError['message'].' ('.$foundError['source'].')'; + + $source = $foundError['source']; + if (in_array($source, $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'], true) === false) { + $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'][] = $source; + } + + if ($foundError['fixable'] === true + && in_array($source, $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'], true) === false + ) { + $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'][] = $source; + } + } + + $allProblems[$line]['found_errors'] = array_merge($foundErrorsTemp, $errorsTemp); + }//end foreach + + if (isset($expectedErrors[$line]) === true) { + $allProblems[$line]['expected_errors'] = $expectedErrors[$line]; + } else { + $allProblems[$line]['expected_errors'] = 0; + } + + unset($expectedErrors[$line]); + }//end foreach + + foreach ($expectedErrors as $line => $numErrors) { + if (isset($allProblems[$line]) === false) { + $allProblems[$line] = [ + 'expected_errors' => 0, + 'expected_warnings' => 0, + 'found_errors' => [], + 'found_warnings' => [], + ]; + } + + $allProblems[$line]['expected_errors'] = $numErrors; + } + + foreach ($foundWarnings as $line => $lineWarnings) { + foreach ($lineWarnings as $column => $warnings) { + if (isset($allProblems[$line]) === false) { + $allProblems[$line] = [ + 'expected_errors' => 0, + 'expected_warnings' => 0, + 'found_errors' => [], + 'found_warnings' => [], + ]; + } + + $foundWarningsTemp = []; + foreach ($allProblems[$line]['found_warnings'] as $foundWarning) { + $foundWarningsTemp[] = $foundWarning; + } + + $warningsTemp = []; + foreach ($warnings as $warning) { + $warningsTemp[] = $warning['message'].' ('.$warning['source'].')'; + + $source = $warning['source']; + if (in_array($source, $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'], true) === false) { + $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'][] = $source; + } + + if ($warning['fixable'] === true + && in_array($source, $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'], true) === false + ) { + $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'][] = $source; + } + } + + $allProblems[$line]['found_warnings'] = array_merge($foundWarningsTemp, $warningsTemp); + }//end foreach + + if (isset($expectedWarnings[$line]) === true) { + $allProblems[$line]['expected_warnings'] = $expectedWarnings[$line]; + } else { + $allProblems[$line]['expected_warnings'] = 0; + } + + unset($expectedWarnings[$line]); + }//end foreach + + foreach ($expectedWarnings as $line => $numWarnings) { + if (isset($allProblems[$line]) === false) { + $allProblems[$line] = [ + 'expected_errors' => 0, + 'expected_warnings' => 0, + 'found_errors' => [], + 'found_warnings' => [], + ]; + } + + $allProblems[$line]['expected_warnings'] = $numWarnings; + } + + // Order the messages by line number. + ksort($allProblems); + + foreach ($allProblems as $line => $problems) { + $numErrors = count($problems['found_errors']); + $numWarnings = count($problems['found_warnings']); + $expectedErrors = $problems['expected_errors']; + $expectedWarnings = $problems['expected_warnings']; + + $errors = ''; + $foundString = ''; + + if ($expectedErrors !== $numErrors || $expectedWarnings !== $numWarnings) { + $lineMessage = "[LINE $line]"; + $expectedMessage = 'Expected '; + $foundMessage = 'in '.basename($testFile).' but found '; + + if ($expectedErrors !== $numErrors) { + $expectedMessage .= "$expectedErrors error(s)"; + $foundMessage .= "$numErrors error(s)"; + if ($numErrors !== 0) { + $foundString .= 'error(s)'; + $errors .= implode(PHP_EOL.' -> ', $problems['found_errors']); + } + + if ($expectedWarnings !== $numWarnings) { + $expectedMessage .= ' and '; + $foundMessage .= ' and '; + if ($numWarnings !== 0) { + if ($foundString !== '') { + $foundString .= ' and '; + } + } + } + } + + if ($expectedWarnings !== $numWarnings) { + $expectedMessage .= "$expectedWarnings warning(s)"; + $foundMessage .= "$numWarnings warning(s)"; + if ($numWarnings !== 0) { + $foundString .= 'warning(s)'; + if (empty($errors) === false) { + $errors .= PHP_EOL.' -> '; + } + + $errors .= implode(PHP_EOL.' -> ', $problems['found_warnings']); + } + } + + $fullMessage = "$lineMessage $expectedMessage $foundMessage."; + if ($errors !== '') { + $fullMessage .= " The $foundString found were:".PHP_EOL." -> $errors"; + } + + $failureMessages[] = $fullMessage; + }//end if + }//end foreach + + return $failureMessages; + + }//end generateFailureMessages() + + + /** + * Get a list of CLI values to set before the file is tested. + * + * @param string $filename The name of the file being tested. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function setCliValues($filename, $config) + { + + }//end setCliValues() + + + /** + * Returns the lines where errors should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of errors that should occur on that line. + * + * @return array + */ + abstract protected function getErrorList(); + + + /** + * Returns the lines where warnings should occur. + * + * The key of the array should represent the line number and the value + * should represent the number of warnings that should occur on that line. + * + * @return array + */ + abstract protected function getWarningList(); + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/Standards/AllSniffs.php b/vendor/squizlabs/php_codesniffer/tests/Standards/AllSniffs.php new file mode 100644 index 0000000..e355d90 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/Standards/AllSniffs.php @@ -0,0 +1,114 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests\Standards; + +use PHP_CodeSniffer\Util\Standards; +use PHP_CodeSniffer\Autoload; +use PHPUnit\TextUI\TestRunner; +use PHPUnit\Framework\TestSuite; + +class AllSniffs +{ + + + /** + * Prepare the test runner. + * + * @return void + */ + public static function main() + { + TestRunner::run(self::suite()); + + }//end main() + + + /** + * Add all sniff unit tests into a test suite. + * + * Sniff unit tests are found by recursing through the 'Tests' directory + * of each installed coding standard. + * + * @return \PHPUnit\Framework\TestSuite + */ + public static function suite() + { + $GLOBALS['PHP_CODESNIFFER_SNIFF_CODES'] = []; + $GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES'] = []; + $GLOBALS['PHP_CODESNIFFER_SNIFF_CASE_FILES'] = []; + + $suite = new TestSuite('PHP CodeSniffer Standards'); + + $isInstalled = !is_file(__DIR__.'/../../autoload.php'); + + // Optionally allow for ignoring the tests for one or more standards. + $ignoreTestsForStandards = getenv('PHPCS_IGNORE_TESTS'); + if ($ignoreTestsForStandards === false) { + $ignoreTestsForStandards = []; + } else { + $ignoreTestsForStandards = explode(',', $ignoreTestsForStandards); + } + + $installedStandards = self::getInstalledStandardDetails(); + + foreach ($installedStandards as $standard => $details) { + Autoload::addSearchPath($details['path'], $details['namespace']); + + if (in_array($standard, $ignoreTestsForStandards, true) === true) { + continue; + } + + $testsDir = $details['path'].DIRECTORY_SEPARATOR.'Tests'.DIRECTORY_SEPARATOR; + if (is_dir($testsDir) === false) { + // No tests for this standard. + continue; + } + + $di = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($testsDir)); + + foreach ($di as $file) { + // Skip hidden files. + if (substr($file->getFilename(), 0, 1) === '.') { + continue; + } + + // Tests must have the extension 'php'. + $parts = explode('.', $file); + $ext = array_pop($parts); + if ($ext !== 'php') { + continue; + } + + $className = Autoload::loadFile($file->getPathname()); + $GLOBALS['PHP_CODESNIFFER_STANDARD_DIRS'][$className] = $details['path']; + $GLOBALS['PHP_CODESNIFFER_TEST_DIRS'][$className] = $testsDir; + $suite->addTestSuite($className); + } + }//end foreach + + return $suite; + + }//end suite() + + + /** + * Get the details of all coding standards installed. + * + * @return array + * @see Standards::getInstalledStandardDetails() + */ + protected static function getInstalledStandardDetails() + { + return Standards::getInstalledStandardDetails(true); + + }//end getInstalledStandardDetails() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/TestSuite.php b/vendor/squizlabs/php_codesniffer/tests/TestSuite.php new file mode 100644 index 0000000..ff7bde7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/TestSuite.php @@ -0,0 +1,35 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests; + +use PHPUnit\Framework\TestSuite as PHPUnit_TestSuite; +use PHPUnit\Framework\TestResult; + +class TestSuite extends PHPUnit_TestSuite +{ + + + /** + * Runs the tests and collects their result in a TestResult. + * + * @param \PHPUnit\Framework\TestResult $result A test result. + * + * @return \PHPUnit\Framework\TestResult + */ + public function run(TestResult $result=null) + { + $result = parent::run($result); + printPHPCodeSnifferTestOutput(); + return $result; + + }//end run() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/TestSuite7.php b/vendor/squizlabs/php_codesniffer/tests/TestSuite7.php new file mode 100644 index 0000000..a4dabf5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/TestSuite7.php @@ -0,0 +1,35 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +namespace PHP_CodeSniffer\Tests; + +use PHPUnit\Framework\TestSuite as PHPUnit_TestSuite; +use PHPUnit\Framework\TestResult; + +class TestSuite extends PHPUnit_TestSuite +{ + + + /** + * Runs the tests and collects their result in a TestResult. + * + * @param \PHPUnit\Framework\TestResult $result A test result. + * + * @return \PHPUnit\Framework\TestResult + */ + public function run(TestResult $result=null): TestResult + { + $result = parent::run($result); + printPHPCodeSnifferTestOutput(); + return $result; + + }//end run() + + +}//end class diff --git a/vendor/squizlabs/php_codesniffer/tests/bootstrap.php b/vendor/squizlabs/php_codesniffer/tests/bootstrap.php new file mode 100644 index 0000000..8d91b15 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/tests/bootstrap.php @@ -0,0 +1,84 @@ + + * @copyright 2006-2017 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ + +if (defined('PHP_CODESNIFFER_IN_TESTS') === false) { + define('PHP_CODESNIFFER_IN_TESTS', true); +} + +if (defined('PHP_CODESNIFFER_CBF') === false) { + define('PHP_CODESNIFFER_CBF', false); +} + +if (defined('PHP_CODESNIFFER_VERBOSITY') === false) { + define('PHP_CODESNIFFER_VERBOSITY', 0); +} + +if (is_file(__DIR__.'/../autoload.php') === true) { + include_once __DIR__.'/../autoload.php'; +} else { + include_once 'PHP/CodeSniffer/autoload.php'; +} + +$tokens = new \PHP_CodeSniffer\Util\Tokens(); + +// Compatibility for PHPUnit < 6 and PHPUnit 6+. +if (class_exists('PHPUnit_Framework_TestSuite') === true && class_exists('PHPUnit\Framework\TestSuite') === false) { + class_alias('PHPUnit_Framework_TestSuite', 'PHPUnit'.'\Framework\TestSuite'); +} + +if (class_exists('PHPUnit_Framework_TestCase') === true && class_exists('PHPUnit\Framework\TestCase') === false) { + class_alias('PHPUnit_Framework_TestCase', 'PHPUnit'.'\Framework\TestCase'); +} + +if (class_exists('PHPUnit_TextUI_TestRunner') === true && class_exists('PHPUnit\TextUI\TestRunner') === false) { + class_alias('PHPUnit_TextUI_TestRunner', 'PHPUnit'.'\TextUI\TestRunner'); +} + +if (class_exists('PHPUnit_Framework_TestResult') === true && class_exists('PHPUnit\Framework\TestResult') === false) { + class_alias('PHPUnit_Framework_TestResult', 'PHPUnit'.'\Framework\TestResult'); +} + + +/** + * A global util function to help print unit test fixing data. + * + * @return void + */ +function printPHPCodeSnifferTestOutput() +{ + echo PHP_EOL.PHP_EOL; + + $output = 'The test files'; + $data = []; + + $codeCount = count($GLOBALS['PHP_CODESNIFFER_SNIFF_CODES']); + if (empty($GLOBALS['PHP_CODESNIFFER_SNIFF_CASE_FILES']) === false) { + $files = call_user_func_array('array_merge', $GLOBALS['PHP_CODESNIFFER_SNIFF_CASE_FILES']); + $files = array_unique($files); + $fileCount = count($files); + + $output = '%d sniff test files'; + $data[] = $fileCount; + } + + $output .= ' generated %d unique error codes'; + $data[] = $codeCount; + + if ($codeCount > 0) { + $fixes = count($GLOBALS['PHP_CODESNIFFER_FIXABLE_CODES']); + $percent = round(($fixes / $codeCount * 100), 2); + + $output .= '; %d were fixable (%d%%)'; + $data[] = $fixes; + $data[] = $percent; + } + + vprintf($output, $data); + +}//end printPHPCodeSnifferTestOutput() diff --git a/vendor/symfony/deprecation-contracts/CHANGELOG.md b/vendor/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/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/vendor/symfony/deprecation-contracts/LICENSE b/vendor/symfony/deprecation-contracts/LICENSE new file mode 100644 index 0000000..0ed3a24 --- /dev/null +++ b/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/vendor/symfony/deprecation-contracts/README.md b/vendor/symfony/deprecation-contracts/README.md new file mode 100644 index 0000000..9814864 --- /dev/null +++ b/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/vendor/symfony/deprecation-contracts/composer.json b/vendor/symfony/deprecation-contracts/composer.json new file mode 100644 index 0000000..c6d02d8 --- /dev/null +++ b/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/vendor/symfony/deprecation-contracts/function.php b/vendor/symfony/deprecation-contracts/function.php new file mode 100644 index 0000000..2d56512 --- /dev/null +++ b/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); + } +}